我有以下代码,我想将小部件初始化为默认值,但他们坚持不这样做。我设置StringVar()变量,我分配它们,但它仍然无法正常工作。有什么建议吗?
import tkinter as tk
from tkinter import ttk
class popup():
def __init__(self):
edit_window=tk.Toplevel()
works_checkbutton_val=[tk.IntVar()]*7
start_time_combo_val=[tk.StringVar()]*7
end_time_combo_val=[tk.StringVar()]*7
datapoint=['Joe Blow','8 AM to 5 PM','8 AM to 5 PM','8 AM to 5 PM','8 AM to 5 PM','8 AM to 5 PM','8 AM to 5 PM','8 AM to 5 PM','3foobarIID']
headings =['Employee Name','Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']
for row in range(1,len(datapoint)-1):
ttk.Label(edit_window, text=headings[row]).grid(row=row+1, column=0, sticky='e', pady=((7.5,0),(7.5,7.5))[row==len(datapoint)-2], padx=5)
ttk.Label(edit_window, text=headings[0]).grid(row=0, column=0, sticky='e', pady=(7.5,0), padx=5)
employee_name_entry = ttk.Entry(edit_window)
employee_name_entry.insert(0, datapoint[0])
employee_name_entry.grid(row=0, column=1, columnspan=4, pady=(7.5,0), padx=5, sticky='ew')
works_checkbutton=[]
start_time_combo=[]
end_time_combo=[]
for row in range(1,len(datapoint)-1):
split_time=datapoint[row].split(' to ')
if len(split_time)==1:
works_checkbutton_val[row-1].set(0)
start_time_combo_val[row-1].set('0 AM')
end_time_combo_val[row-1].set('0 AM')
else:
works_checkbutton_val[row-1].set(1)
start_time_combo_val[row-1].set(split_time[0])
end_time_combo_val[row-1].set(split_time[1])
works_checkbutton.append(ttk.Checkbutton(edit_window, variable = works_checkbutton_val[row-1]))
works_checkbutton[row-1].grid(row=row+1, column=1, padx=2.5, pady=(0,(0,7.5))[row==len(datapoint)-2], sticky='s')
start_time_combo.append(ttk.Combobox(edit_window, values=["%s AM"%(x+1) for x in range(12)] + ["%s PM"%(x+1) for x in range(12)],textvariable=start_time_combo_val[row-1]))
start_time_combo[row-1].grid(row=row+1, column=4, pady=((7.5,0),(7.5,7.5))[row==len(datapoint)-2], padx=5)
end_time_combo.append(ttk.Combobox(edit_window, values=["%s AM"%(x+1) for x in range(12)] + ["%s PM"%(x+1) for x in range(12)],textvariable=end_time_combo_val[row-1]))
end_time_combo[row-1].grid(row=row+1, column=3, pady=((7.5,0),(7.5,7.5))[row==len(datapoint)-2], padx=5)
main_window=tk.Tk()
b1 = ttk.Button(main_window,text='here',command=lambda:popup())
b1.pack()
main_window.mainloop()
答案 0 :(得分:1)
IntVar
,StringVar
变量存储在局部变量中。一旦popup
函数返回,它们就会消失。
你需要保留它们(至少在Toplevel有效之前)。例如,以下行将变量保存为edit_window
的实例变量,以便在edit_window
顶层有效时它们能够存活。
edit_window.vals1 = works_checkbutton_val = [tk.IntVar() for i in range(7)]
edit_window.vals2 = start_time_combo_val = [tk.StringVar() for i in range(7)]
edit_window.vals3 = end_time_combo_val = [tk.StringVar() for i in range(7)]