我正在使用 tkinter,我的目标是每当我点击第 2 页时在类 Page2(Page)
中打印列表 L。目前,如果您运行代码,您可以看到字母 A 和 B 正在打印在进入第 1 页后的控制台,这意味着 tkinter 已经完成了 for 循环。仅当我单击第 2 页时,如何更改此代码以执行该 for 循环?仅供参考,我从 Using buttons in Tkinter to navigate to different pages of the application? 的答案中借用了代码。
import tkinter as tk
class Page(tk.Frame):
def __init__(self, *args, **kwargs):
tk.Frame.__init__(self, *args, **kwargs)
def show(self):
self.lift()
class Page1(Page):
def __init__(self, *args, **kwargs):
Page.__init__(self, *args, **kwargs)
label = tk.Label(self, text="This is page 1")
label.pack(side="top", fill="both", expand=True)
class Page2(Page):
def __init__(self, *args, **kwargs):
Page.__init__(self, *args, **kwargs)
L=[]
for x in ["A","B"]:
print(x)
L.append(x)
label = tk.Label(self, text=L)
label.pack(side="top", fill="both", expand=True)
class Page3(Page):
def __init__(self, *args, **kwargs):
Page.__init__(self, *args, **kwargs)
label = tk.Label(self, text="This is page 3")
label.pack(side="top", fill="both", expand=True)
class MainView(tk.Frame):
def __init__(self, *args, **kwargs):
tk.Frame.__init__(self, *args, **kwargs)
p1 = Page1(self)
p2 = Page2(self)
p3 = Page3(self)
buttonframe = tk.Frame(self)
container = tk.Frame(self)
buttonframe.pack(side="top", fill="x", expand=False)
container.pack(side="top", fill="both", expand=True)
p1.place(in_=container, x=0, y=0, relwidth=1, relheight=1)
p2.place(in_=container, x=0, y=0, relwidth=1, relheight=1)
p3.place(in_=container, x=0, y=0, relwidth=1, relheight=1)
b1 = tk.Button(buttonframe, text="Page 1", command=p1.lift)
b2 = tk.Button(buttonframe, text="Page 2", command=p2.lift)
b3 = tk.Button(buttonframe, text="Page 3", command=p3.lift)
b1.pack(side="left")
b2.pack(side="left")
b3.pack(side="left")
p1.show()
if __name__ == "__main__":
root = tk.Tk()
main = MainView(root)
main.pack(side="top", fill="both", expand=True)
root.wm_geometry("400x400")
root.mainloop()
答案 0 :(得分:1)
它正在打印列表,因为这是创建 Page2
类实例的一部分,该实例发生在它可见之前(如果有的话)——这只是你“借用”的答案中代码架构的产物”。
这是一种解决问题的方法。首先更改 Button
中的 command=
回调 MainView.__init__()
选项,以便调用 show()
方法而不是 lift()
:
b1 = tk.Button(buttonframe, text="Page 1", command=p1.show)
b2 = tk.Button(buttonframe, text="Page 2", command=p2.show)
b3 = tk.Button(buttonframe, text="Page 3", command=p3.show)
这意味着现在只要点击 Page
之一,就会调用每个 show()
子类的 Button
方法,默认情况下它只会调用其基类 {{1} } 方法,因此所有这些都添加了一个间接级别 - 从而可以轻松地在 lift()
等子类中覆盖/扩展它,以使它们执行可能需要的任何专门处理。
请注意,我还使 Page2
成为子类实例的属性(而不是 L
方法中的局部变量)以允许它很容易在类的其他方法中引用。
__init__()