Unable to bind function after pickling - tkinter - python-3.x

I have simple code which creates two fields by the press of a button. There are two other buttons to save and load back the entry fields created. I have used the bind function to bind field A and field B. Pressing the Enter button on field A after entering a number will print out its value multiplied by 5 in field B. At this point the bind function works perfectly.
When I create three entry fields and save the progress without entering any inputs and compile the program, then load the file, the bind function does not seem to work. It seems to work only for the last field created. My code is as follows. I tried my best to simplify the code.
from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import asksaveasfile
from tkinter import messagebox
import pickle
class Test(Frame):
def Widgets(self):
self.button_add = Button(self, text = "Add", command = self.add)
self.button_add.grid(row=0, column =2)
self.button_save = Button(self, text = "save", command = self.save)
self.button_save.grid(row=0, column =3)
self.button_load = Button(self, text = "load", command = self.load)
self.button_load.grid(row=0, column =4)
def add(self):
def test(event):
self.field_B[n].delete(0, END)
self.field_B[n].insert(0, (float(self.field_A[n].get()))*5)
self.field_A.append({})
n = len(self.field_A)-1
self.field_A[n] = Entry(self)
self.field_A[n].grid(row=n, column =0)
self.field_A[n].bind("<Return>", test)
self.field_B.append({})
n = len(self.field_B)-1
self.field_B[n] = Entry(self)
self.field_B[n].grid(row=n, column =1)
def save(self):
for n in range(len(self.field_A)):
self.entry_A.append(self.field_A[n].get())
self.entry_B.append(self.field_B[n].get())
fname = asksaveasfile(mode = "w", defaultextension = ".est")
data = {"fields": len(self.field_A), "entries_A": (self.entry_A),"entries_B": (self.entry_B)}
with open(fname.name, "wb") as file:
pickle.dump(data, file)
def load(self):
def test(event):
print("Why is the value of n always equal to", n, "?")
self.field_B[n].delete(0, END)
self.field_B[n].insert(0, (float(self.field_A[n].get()))*5)
fname = askopenfilename(filetypes = (("Estimation Files (est)", "*.est"),))
location = fname.replace("/", "\\")
if location:
with open(location, "rb") as file:
data = pickle.load(file)
for n in range(data["fields"]):
self.field_A.append({})
self.field_A[n] = Entry(self)
self.field_A[n].grid(row=n, column =0)
self.field_A[n].insert(0, data["entries_A"][n])
self.field_A[n].bind("<Return>", test)
self.field_B.append({})
self.field_B[n] = Entry(self)
self.field_B[n].grid(row=n, column =1)
self.field_B[n].insert(0, data["entries_B"][n])
def __init__(self,master = None):
Frame.__init__(self, master)
self.field_A = []
self.field_B = []
self.entry_A = []
self.entry_B = []
self.grid()
self.Widgets()
root = Tk()
app = Test(master = None)
app.mainloop()

You need a "closure". You can make a closure in python with the functools.partial function.
from functools import partial
def test(n, event=None):
self.field_B[n].delete(0, END)
self.field_B[n].insert(0, (float(self.field_A[n].get()))*5)
#other code ...
self.field_A[n].bind("<Return>", partial(test, n))

Both of your test() functions are accessing a variable n from the enclosing function. In the case of add(), there is no loop; n has a single value. Each Entry's test() gets its own n, because they were bound by a distinct call to add(). In load(), however, you are looping over n values; each test() is referring to the same n, which will have its final value by the time that any binding can possibly be invoked. The other answer gives a reasonable way to give each instance of test() its own personal n, so I'm not going to repeat that here.

Related

how to differentiate between color and value in send cellchanged signal

There is a table with some values in it. what I am trying to do is to capture changes of the table content and save them inside a SQLite database. so I connected table to cellChanged and itemSelectionChanged signals. when I try to change some cells content, it will check it to verify it does not contain letters, and it's a number. so if after changing the cell, it has letters inside, it will try to rechange the content to its previous value.
I also have a search toolbar to search in table for some keyword. what the search toolbar does, is to colorize the cells that matching that specific keyword. but in doing so, it emits cellChanged signal and not cellSelectionChanged signal. that causes an error (myapp object has no attribute previous_value), because I haven't selected any cell yet. But if I select a cell and then start seeking, writing anything inside search box will change the content of every cell, because it is triggering cellChanged signal. my question is how to differentiate between color and text changes in cellChanged function. thank you in advance.
here is the sample code:(python 3.7.4, pyqt5 5.13.0)
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import sys
class myapp(QWidget):
def __init__(self):
QWidget.__init__(self)
self.tableWidget = QTableWidget()
self.tableWidget.setSortingEnabled(True)
self.tableWidget.setRowCount(5)
self.tableWidget.setColumnCount(5)
for i in range(5):
for j in range(5):
item=QTableWidgetItem("cell["+str(i) + ","+ str(j) + "]")
self.tableWidget.setItem(i,j,item)
self.tableWidget.cellChanged.connect(self.on_tablewidget_cell_changed)
self.tableWidget.itemSelectionChanged.connect(self.on_tablewidget_item_selection_changed)
self.search_entry = QLineEdit()
self.search_entry.textChanged.connect(self.seek)
layout = QVBoxLayout()
layout.addWidget(self.tableWidget)
layout.addWidget(self.search_entry)
self.setLayout(layout)
def on_tablewidget_cell_changed(self,row,col):
value = self.tableWidget.item(row,col).text()
if not self.check_numeric(value):
self.tableWidget.item(row,col).setText(self.previous_value)
def on_tablewidget_item_selection_changed(self):
row = self.tableWidget.currentRow()
col = self.tableWidget.currentColumn()
self.previous_value = self.tableWidget.item(row,col).text()
def seek(self):
keyword = self.search_entry.text()
items = self.tableWidget.findItems(keyword, Qt.MatchContains)
for item in items:
item.setBackground(Qt.red)
def check_numeric(self,value):
value = value.strip()
tmp = "".join([i for i in value if i in "0123456789"])
return(len(value) == len(tmp))
app = QApplication(sys.argv)
win = myapp()
win.show()
sys.exit(app.exec_())
Instead of capturing cellChanged signals to check if the user input is valid, you could set an item delegate for the table widget, and check the user input in there before setting the model data. For example:
class IntItemDelegate(QItemDelegate):
def setModelData(self, editor, item_model, model_index):
# only update the model data if the user input consists of digits only.
text = editor.text()
if self.check_numeric(text):
item_model.setData(model_index, text)
def check_numeric(self, value):
return value.isdecimal()
class myapp(QWidget):
def __init__(self):
QWidget.__init__(self)
self.tableWidget = QTableWidget()
self.tableWidget.setSortingEnabled(True)
self.tableWidget.setRowCount(5)
self.tableWidget.setColumnCount(5)
for i in range(5):
for j in range(5):
item=QTableWidgetItem("cell["+str(i) + ","+ str(j) + "]")
self.tableWidget.setItem(i,j,item)
# set a custom item delegate which will take care of checking the user input
self.tableWidget.setItemDelegate( IntItemDelegate())
self.search_entry = QLineEdit()
self.search_entry.textChanged.connect(self.seek)
layout = QVBoxLayout()
layout.addWidget(self.tableWidget)
layout.addWidget(self.search_entry)
self.setLayout(layout)
def seek(self):
keyword = self.search_entry.text()
items = self.tableWidget.findItems(keyword, Qt.MatchContains)
for item in items:
item.setBackground(Qt.red)

How do I get the value from an option in tkinter after it has passed through a function?

I'm using tkinter to create an option menu for a user to interact with, when the selection has been made it will pass through a function to return an integer based on the input. I want to be able to return the integer back to a variable outside of the function so it can be received by another file. My problem is that python will keep returning the button as the command has not yet been processed.
from tkinter import *
Final = [] ##List containing options
master = Tk()
variable = StringVar(master)
variable.set(Final[0]) # default value
w = OptionMenu(master, variable, *Final)
w.pack()
def ok():
global choice
choice = variable.get()
global x
x = 0
for i in Final:
if str(i) == str(choice):
break
x += 1
button = Button(master, text="Choose", command=ok)
button.pack()
values = x

N is not defined (Global Present)

So I'm currently doing a project that is a random generator that reads on an excel file and select a data randomly but as I develop my code I get the following error:
line 19, in RandomG
L2 = Label(r2, text=edata).grid(row=3, column=1).grid(rowspawn=3, sticky=S)
NameError: name 'edata' is not defined
I have been told once to use "global" so the variables applies to all functions
but it still gives me the error.
Here is my code:
from tkinter import *
from tkinter import ttk
from tkinter.filedialog import askopenfilename
import xlrd
import random
import os
creds = 'Python file.txt' # This just sets the variable creds to 'tempfile.temp'
def RandomG():
global r2
r.destroy()
rootA.destroy()
r2 = Tk()
r2.title('Random Generator')
r2.geometry('350x300')
r2.resizable(False, False)
L1 = Label(r2, text='Welcome to My Random Generator!!').grid(row=1, column=1)
L2 = Label(r2, text= edata).grid(row=3, column=1).grid(rowspawn=3, sticky=S)
L2.config(width=200)
B1 = Button(r2, text="Browse", command=Directory)
B1.grid(rowspan=3, sticky=S)
B2 = Button(r2, text="Randomize", command=Generator)
B2.grid(rowspan=3, sticky=S)
r2.mainloop
def Directory():
global filename
filename = askopenfilename(filetypes=(("Excel Files", ".xlsx"),("All files","*.*")))
pathlabel = Label(r2)
pathlabel.config(text=(filename))
pathlabel.grid(columnspan=2)
pathlabel.pack()
def Generator():
global edata
global sheet
global workbook
with open(filename)as a:
filelocation = (filename)
workbook = xlrd.open_workbook(filelocation)
sheet = workbook.sheet_by_index(0)
for col in range(sheet.nrows):
edata = print[sheet.pop(sheet.random.cell.value(0, col))]
this is not how the global keyword works... global just tells your function to look up the variable in the global namespace (instead of the local namespace of your function).
this would work:
N = None
def f():
global N
print(N)
without defining N first (or setting it inside your function) it will not.
this would also work:
def f():
global N
N = 5
print(N)
(and it would spill N to your global namespace).
in any case: you have to set N (or edata in your case) before you try to read its value.
This means that edata doesn't have a value. It needs to be defined before calling it.

How to store in variables current row selection within tree widget to query a database using python

I wonder if it is possible to store in variables the contents from a tree widget row (when it is selected with the mouse) see picture. Basically I want to sync my tree with a database, every time when I insert or delete an element in my tree, my database needs to auto update.
With the insert part it is not a problem , because I have entry widgets, but I don't know how to manage the delete part. Therefore, I wonder if it is possible to do this with some cursor selection function.
I have been trying for a very long time to find a solution for this, I would really appreciate if someone can help me with some hints
Code:
import tkinter
from tkinter import ttk
class cards(tkinter.Frame):
def __init__(self, parent):
tkinter.Frame.__init__(self, parent)
self.parent=parent
self.parent.geometry("800x500")
self.initialize_user_interface()
def initialize_user_interface(self):
self.parent.title("cards")
self.parent.grid_rowconfigure(0,weight=1)
self.parent.grid_columnconfigure(0,weight=1)
self.parent.config(background="lavender")
self.Card_label = tkinter.Label(self.parent, text = "Card type:")
self.Card_entry = tkinter.Entry(self.parent)
self.Card_label.place(x=5,y=5)
self.Card_entry.place(x=70,y=5)
self.SN_label = tkinter.Label(self.parent, text = "SN:")
self.SN_entry = tkinter.Entry(self.parent)
self.SN_label.place(x=5,y=40)
self.SN_entry.place(x=70,y=40)
self.submit_button = tkinter.Button(self.parent, text = "Insert", command = self.insert_data)
self.submit_button.place(x=210,y=15)
self.exit_button = tkinter.Button(self.parent, text = "Exit", command = self.exit)
self.exit_button.place(x=270,y=15)
self.tree = ttk.Treeview( self.parent, columns=('Card Type', 'SN'))
self.tree.heading('#0', text='Nr.')
self.tree.heading('#1', text='Card Type')
self.tree.heading('#2', text='SN')
self.tree.column('#1', stretch=tkinter.YES)
self.tree.column('#2', stretch=tkinter.YES)
self.tree.column('#0', stretch=tkinter.YES)
self.tree.place(x=0,y=100)
self.treeview = self.tree
self.i = 1
def exit(self):
self.master.destroy()
def insert_data(self):
self.treeview.insert('', 'end', text=str(self.i), values=(self.Card_entry.get(), self.SN_entry.get()))
self.i = self.i + 1
def main():
root=tkinter.Tk()
d=cards(root)
root.mainloop()
if __name__=="__main__":
main()
You can use
for item in self.tree.selection():
print(self.tree.item(item, "text"))
print(self.tree.item(item, "values"))
#print(self.tree.item(item))
to see data from all selected rows - you can select more than one row.
You can use it in function assigned to button
or you can use bind() to assign function to mouse click on row.

Making a basic user interface with tkinter-python

I've just been trying to practice some code by making a simple dice game
and using tkinter for the user interface of the starting menu for the game
For the starting menu, I'm trying to just see how it will come out if I used the code below,
BUT before making the Button widget and the Label Widgets, the commands come up first.
How would I fix this up?
thanks in advance
import tkinter as tk
from main import main
from written import showInstructions, showCredits
from generate_no import generate_no
class DiceGameUI(tk.Frame):
def __init__(self, master = None):
tk.Frame.__init__(self, master)
self.grid()
self.createWidgets()
def createWidgets(self):
self.titleLabel = tk.Label(self, fg = "red") #The Title of the Game
self.titleLabel["text"] = "Dice Game"
self.startButton = tk.Button(self) #Start Button
self.startButton["text"] = "Roll On!"
self.startButton["command"] = main() <<----- This plays out first before
self.startButton.grid() making any widgets
self.instrButton = tk.Button(self) #Instructions Button
self.instrButton["text"] = "Instructions"
self.instrButton["command"] = showInstructions()
self.instrButton.grid()
self.credits = tk.Button(self) #Credits Button
self.credits["text"] = "Credits"
self.credits["command"] = showCredits()
self.credits.grid()
root = tk.Tk() #Run code using tkinter
app = DiceGameUI(master = root)
app.mainloop()
'
You have to assign only name of function without () and arguments
self.startButton["command"] = main
If you use () than you run that function and result is assigned to command. It is good to create dynamicly function for command.
If you will need assign function which require arguments you have to use lambda function.
self.startButton["command"] = lambda:main()
self.startButton["command"] = lambda:main("abc", 123)
a = "abc"
b = 123
self.startButton["command"] = lambda arg1=a,arg2=b:main(arg1,arg2)
self.startButton["command"] = lambda title=a,count=b:main(title,count)
# this may not work - especially if a or b changes value (for example in loop)
self.startButton["command"] = lambda:main(a, b)
example how to use function name in own code
def plus(a, b):
return a + b
def minus(a, b):
return a - b
def result(a, b, func_name):
return func_name(a,b)
print result(10, 7, plus) # 17
print result(10, 7, minus) # 3

Resources