当实现复杂的对话框(即具有大约10个或更多小部件的对话框,特别是当排列在多个框架中时,创建需要许多tkinter调用,并且当代码保存在单个方法中时,代码可能会变得越来越复杂(难以阅读和维护(。此外,一般来说,短函数/方法通常比长函数/方法更受欢迎。
我目前限制方法长度的方法是将属于对话框中某个组的所有小部件的创建封装到一个返回顶级小部件的method(parent_frame, other_options)
中,如下所示:
import tkinter as tk
class Dialog:
def __init__(self, master):
self.__master = master
self.create_gui(master)
def create_gui(self, frame, title = None):
if title: frame.title(title)
group_a = self.create_group_a(frame)
group_a.grid(row=0, column=0, sticky="nsew")
group_b = self.create_group_b(frame)
group_b.grid(row=1, column=0, sticky="nsew")
frame.columnconfigure(0, weight=1)
frame.rowconfigure(0, weight=1)
frame.rowconfigure(1, weight=1)
def create_group_a(self, frame):
inner_frame = tk.LabelFrame(frame, text="Label")
text = self.create_text_with_scrollbar(inner_frame)
text.pack(fill="both")
return inner_frame
def create_group_b(self, frame):
button = tk.Button(frame, text="Button")
return button
def create_text_with_scrollbar(self, frame):
text_frame = tk.Frame(frame)
text_frame.grid_rowconfigure(0, weight=1)
text_frame.grid_columnconfigure(0, weight=1)
text = tk.Text(text_frame)
text.grid(row=0, column=0, sticky="nsew")
scrollbar = tk.Scrollbar(text_frame, command=text.yview)
scrollbar.grid(row=0, column=1, sticky="nsew")
text['yscrollcommand'] = scrollbar.set
return text_frame
if __name__ == "__main__":
master = tk.Tk()
Dialog(master)
tk.mainloop()
在这种情况下,是否有关于代码结构的具体准则?有人对如何更好地构建这样的代码有任何建议吗?
我通常做的是为每个组编写一个新类。这些类继承自 Frame。最终结果将如下所示:
class MainFrame(Frame):
def __init__(self, *args, **kwargs):
super().__init__(self, *args, **kwargs)
self.first_sub = FirstSubFrame(self)
self.second_sub = SecondSubFrame(self)
self.first_sub.grid()
self.second_sub.grid()
class FirstSubFrame(Frame):
def __init__(self, *args, **kwargs):
super().__init__(self, *args, **kwargs)
self.possibly_another_subframe = PossibleOtherFrame(self)
self.awesome_button = tkinter.Button()
self.possibly_another_subframe.grid()
self.awesome_button.grid()
...
我希望这有所帮助。