我正在尝试在 Tkinter GUI 中创建一堆子帧,每个子帧都包含一些用户输入变量,稍后我需要通过每个子帧的唯一 ID 来获取这些变量。我需要能够随意添加和删除子帧,并以合理的顺序对它们进行标识(目前从 1 开始计数的整数)
三个问题:
1)具体来说,为什么显示每个框架标题的标签小部件不显示?(这可能是愚蠢的事情......)
2) 具体来说,为什么有时需要按两次添加或删除按钮来添加或删除框架?
3)一般来说:有没有更好的方法来解决这个问题?在跟踪框架实例的意义上。他们现在在一个列表中......我早些时候开始使用 dict 但它更难使用......有更好的建议吗?
from tkinter import *
from tkinter.ttk import *
class AllInstances(Tk):
def __init__(self):
Tk.__init__(self)
self.master_frame = Frame(self)
self.master_frame.grid()
self.all_instances = []
root = AllInstances()
class OneInstance():
def __init__(self):
self.number = len(root.all_instances) + 1
var1 = StringVar()
var2 = StringVar()
var3 = StringVar()
self.sub_frame = Frame(root.master_frame)
self.sub_frame.grid(column = self.number, row = 0)
titletext = StringVar()
titletext.set('%s %s' % ('Frame', self.number))
print(titletext.get())
title = Label(self.sub_frame, textvariable = titletext)
title.grid() #work out why this label does not display!
uservar1 = Entry(self.sub_frame, textvariable = var1)
uservar1.grid()
uservar2 = Entry(self.sub_frame, textvariable = var2)
uservar2.grid()
uservar3 = Entry(self.sub_frame, textvariable = var3)
uservar3.grid()
#etc etc
add_button = Button(self.sub_frame, text = 'Add', command = lambda: Create())
add_button.grid()
def RemoveInstance(self):
if len(root.all_instances) > 1:
root.all_instances.remove(self)
self.sub_frame.destroy()
for instance in root.all_instances:
instance.number = (root.all_instances.index(instance) + 1)
else:
pass
remove_button = Button(self.sub_frame, text = 'Remove', command = lambda: RemoveInstance(self))
remove_button.grid()
root.all_instances.append(self)
def Create():
OneInstance()
Create()
root.mainloop()
谢谢... :)