gpt4 book ai didi

python - 在 Toplevel() 窗口中设置默认值

转载 作者:太空宇宙 更新时间:2023-11-03 15:57:00 24 4
gpt4 key购买 nike

我有以下代码,我想将小部件初始化为默认值,但他们坚持不这样做。我正在设置 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()

最佳答案

IntVarStringVar 变量存储在局部变量中。一旦 popup 函数返回,它们就会消失。

您需要保留它们(至少在顶级有效之前)。例如,以下几行将变量保存为 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)]

关于python - 在 Toplevel() 窗口中设置默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40695940/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com