tkinter:单击按钮时如何打印列表? [英] tkinter: How to print a list when a Button is clicked?

查看:40
本文介绍了tkinter:单击按钮时如何打印列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 tkinter,我的目标是每当我点击第 2 页时在 Page2(Page) 类中打印列表 L.目前,如果你运行代码,你可以看到字母 A &一旦您进入第 1 页,B 就会在控制台中打印出来,这意味着 tkinter 已经完成了 for 循环.仅当我单击第 2 页时,如何更改此代码以执行该 for 循环?仅供参考,我从 使用 Tkinter 中的按钮导航到应用程序的不同页面?.

I am using tkinter and my goal is to print list L inside class Page2(Page) whenever I click on Page 2. Currently, if you run the code, you can see that letters A & B are being printed in the console once you are in Page 1 which means that tkinter has already gone through that for loop. How can I change this code to go through that for loop only if I click on Page 2? FYI, I borrowed the code from the answer to 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()

推荐答案

它正在打印列表,因为这是创建 Page2 类实例的一部分,该实例发生在它可见之前(如果有的话)—这只是您借用"的答案中代码架构的产物.

It's printing the list because that's part of creating an instance of the Page2 class that occurs before it's made visible (if ever) — which is just an artifact of the architecture of the code in the answer you "borrowed".

这是一种解决问题的方法.首先更改 MainView.__init__() 中的 Button 回调 command= 选项,这样 show() 方法将得到调用而不是 lift():

Here's a way to fix things. First change the Button callback command= options in MainView.__init__() so the show() method will get called instead of 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 之一时被调用,即默认只调用它的基类的 lift() 方法,所以这只是添加了一个间接级别 - 从而可以轻松地在子类中覆盖/扩展它,例如 Page2 让他们做任何可能需要的特殊处理.

This means that each Page subclass' show() method will now be invoked whenever one of the Buttons is clicked, which by default just calls its base class' lift() method, so all this does is add a level of indirection — thereby making it possible to easily override / extend it in subclasses like Page2 to make them do whatever specialized processing might be needed.

请注意,我还使 L 成为子类实例的 属性(而不是在 __init__() 方法),以便在类的其他方法中轻松引用它.

Note that I also made L an attribute of the subclass' instances (instead of it being a local variable in the the __init__() method) to allow it to be easily referenced in the other method of the class.

class Page2(Page):
    def __init__(self, *args, **kwargs):
        Page.__init__(self, *args, **kwargs)
        self.L = []
        for x in ["A","B"]:
            self.L.append(x)
        label = tk.Label(self, text=self.L)
        label.pack(side="top", fill="both", expand=True)

    def show(self):
        print(f'in class {type(self).__name__}.show()')
        super().show()  # Call superclass' method.
        for x in self.L:
            print(x)

这篇关于tkinter:单击按钮时如何打印列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆