我在回圈中創建了一些小部件。我需要得到所有的價值。我編碼:
from tkinter import *
class App():
def __init__(self):
self.ws = Tk()
self.frame = LabelFrame(self.ws)
self.frame.grid(row=1,column=1)
for i in range(16):
e = Label(self.frame, text=str(i 1) '.')
e.grid(row=i 1, column=1)
e1 = Entry(self.frame, width=8)
e1.grid(row=i 1, column=2)
e2 = Entry(self.frame)
e2.grid(row=i 1, column=3)
check = Checkbutton(self.frame, variable=BooleanVar(), onvalue=True, offvalue=False)
check.grid(row=i 1, column=4, sticky=E)
but = Button(self.ws,text='Get ALL',command=self.getall)
but.grid(row=17,column=1)
self.ws.mainloop()
def getall(self):
list = []
self.frame.update()
print('Child List:',self.frame.winfo_children())
for wid in self.frame.winfo_children():
if isinstance(wid,Entry):
list.append(wid.get())
elif isinstance(wid,Checkbutton):
self.frame.getvar(wid['variable'])
print('List:',list)
if __name__ == '__main__':
App()
它回傳:
return self.tk.getvar(name) .TclError: can't read "PY_VAR0": no such variable
如果我單擊所有復選按鈕,它不會出錯,但會回傳空字串..這里有什么問題?
uj5u.com熱心網友回復:
TKinter 無法檢索復選框的變數,因為您已經在__init__()作用域內動態創建了這些變數,因此這些變數__init__()僅存在于呼叫堆疊中,一旦__init__()完成作業,垃圾收集器就會清除這些變數,因此它們不會由于它們不在您的主堆疊中,因此無法再訪問。
因此,您需要將它們保留在您的主程式堆疊中。我通過添加一個長期存在的dict()用于存盤這些復選框變數來編輯您的代碼,以便以后能夠訪問它們。
from tkinter import *
class App():
def __init__(self):
self.ws = Tk()
self.frame = LabelFrame(self.ws)
self.frame.grid(row=1, column=1)
self.checkboxesValues = dict()
for i in range(16):
self.checkboxesValues[i] = BooleanVar()
self.checkboxesValues[i].set(False)
e = Label(self.frame, text=str(i 1) '.')
e.grid(row=i 1, column=1)
e1 = Entry(self.frame, width=8)
e1.grid(row=i 1, column=2)
e2 = Entry(self.frame)
e2.grid(row=i 1, column=3)
check = Checkbutton(self.frame, variable=self.checkboxesValues[i])
check.grid(row=i 1, column=4, sticky=E)
but = Button(self.ws, text='Get ALL', command=self.getall)
but.grid(row=17, column=1)
self.ws.mainloop()
def getall(self):
list = []
self.frame.update()
print('Child List:', self.frame.winfo_children())
for wid in self.frame.winfo_children():
if isinstance(wid, Entry):
list.append(wid.get())
elif isinstance(wid, Checkbutton):
list.append(self.frame.getvar(wid['variable']))
print('List:', list)
if __name__ == '__main__':
App()
現在,checkboxesValues變數存在于您App的物件堆疊中,因此只要您的物件未被銷毀,您的復選框變數就存在于您的記憶體中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/351968.html
上一篇:如何在python中創建列印功能
