有史以来问的第一个问题!
我是 Python 和 Tkinter 的新手,并按照本指南使用 Tkinter 创建多个窗口:https://www.youtube.com/watch?v=jBUpjijYtCk&list=PLQVvvaa0QuDclKx-QpC9wntnURXVJqLyk&index=4
当用户在第一个窗口中做出选择时,假设我们每个月都有一个按钮,其中三个按钮(六月、七月、八月)代表夏季。
像这样:
months = ["january", "february" and so on]
for i in months[0:2]:
button = tk.Button(self, text=i, command=lambda:controller.show_frame(PageWinter)).pack()
for i in months[2:5]:
button = tk.Button(self, text=i, command=lambda: controller.show_frame(PageSpring)).pack()
现在的问题是我为每个季节创建了一个类。它工作正常,但是,除了季节之外,所有代码都是相同的,所以我想只创建一个类。代码重复并不漂亮:)我的问题是我不知道如何(或者甚至可能)将用户选择的月份(代表某个季节)带到类里面。
现在我有四个不同的类,如下所示:
class PageSpring(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
a whole lot of code
...
...
season=Spring
more code....
mlabel3=tk.Label(self, text="Results:").pack()
mlabel4=tk.Label(self, text=pres).pack()
button2 = tk.Button(self, text="Back to Startpage",
command=lambda: controller.show_frame(StartPage)).pack()
相反,我想要一门这样的类(class),其中季节以某种方式由用户选择带来。我尝试过的方法都没有奏效,这个季节只是不断变得不确定或缺少其他东西。
class Season(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
a whole lot of code
...
...
more code....
mlabel3=tk.Label(self, text="Results:").pack()
mlabel4=tk.Label(self, text=pres).pack()
button2 = tk.Button(self, text="Back to Startpage",
command=lambda: controller.show_frame(StartPage)).pack()
但是我怎样才能把这个季节带到这个普遍的类(class)呢?
最佳答案
您将季节发送到通用类的方式与发送 self
、parent
和 controller
的方式相同:将其传入作为一个论点。
def __init__(self, parent, controller, season):
此外,不要将几何管理与小部件创建链接起来。而不是:
mybutton = Button(parent).pack()
做:
mybutton = Button(parent)
mybutton.pack()
这可能看起来多余,但较短版本最终发生的情况是 button
并不是真正的 Button
- 它是 None
,由 pack()
返回。保存 Button
比保存 None
更有用。
关于Python Tkinter,通过在进入新窗口(新类)时引入变量来避免代码重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29570935/