找到在tkinter中合并多个部件的最佳方法



你们能告诉我合并一些小部件的最好方法是什么吗?这样我就可以毁掉它们或者把它们贴在窗户上?

我有一个方法来做到这一点,但我不知道这是一个有效的方法或不是,因为我使用列表和使用for循环销毁它们。让我知道最好的方法是什么。对不起,我的英语不好,谢谢。

class X(tk.Frame):
def __init__(self):
super().__init__()
self.lst_element = []
self.butt_plus = tk.Button(self, text="+", command=self.add_element)
self.butt_min = tk.Button(self,text="-", command=self.del_element)
self.butt_plus.grid(row=1, column=0,padx = 5, pady=2)
self.butt_min.grid(row=1, column=1,padx = 5, pady=2)
def elements(self):
self.subject = tk.Entry(self, width=15)
self.weight = tk.Entry(self, width=7)
self.dot = tk.Label(self, text="●")
self.arrow = tk.Label(self, text="=>")
self.lst_element.append([self.subject, self.weight, self.dot, self.arrow])
self.dot.grid(row=len(self.lst_element)-1, column=2)
self.subject.grid(row=len(self.lst_element)-1, column=3, padx = 5, pady=2)
self.arrow.grid(row=len(self.lst_element)-1, column=4)
self.weight.grid(row=len(self.lst_element)-1, column=5, padx = 5, pady=2)


def add_element(self):
self.elements()
print(self.lst_element)

def del_element(self):
if len(self.lst_element) != 1:
for e in self.lst_element[-1]:
e.destroy()
self.lst_element.pop()

我建议您将这些小部件放在一个框架中,然后您可以简单地在单击-按钮时销毁该框架:

class X(tk.Frame):
def __init__(self):
super().__init__()
self.lst_element = []
self.butt_plus = tk.Button(self, text="+", command=self.add_element)
self.butt_min = tk.Button(self,text="-", command=self.del_element)
self.butt_plus.grid(row=1, column=0,padx = 5, pady=2)
self.butt_min.grid(row=1, column=1,padx = 5, pady=2)
def elements(self):
frame = tk.Frame(self)
frame.grid(row=len(self.lst_element), column=2)
subject = tk.Entry(frame, width=15)
weight = tk.Entry(frame, width=7)
dot = tk.Label(frame, text="●")
arrow = tk.Label(frame, text="=>")
dot.pack(side=tk.LEFT)
subject.pack(side=tk.LEFT, padx=5, pady=2)
arrow.pack(side=tk.LEFT)
weight.pack(side=tk.LEFT, padx=5, pady=2)
# don't need to save those labels if they are not referenced later
self.lst_element.append([frame, subject, weight])
def add_element(self):
self.elements()
print(self.lst_element)
def del_element(self):
if self.lst_element:
# get the last row and destroy the frame
self.lst_element.pop()[0].destroy()

相关内容

  • 没有找到相关文章

最新更新