显示来自其他对象的标签

时间:2020-01-21 19:23:38

标签: python tkinter

这是我的代码:

import tkinter as tk

class Window(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.container = tk.Frame(self)
        self.container.pack(side="top", fill="both", expand = True)
        self.label1 = tk.Label(self.container, text="label")
        self.label1.pack()
        self.fwd_button = tk.Button(self, text="Continue", command=lambda: books_display(subframe.Main_Title))
        self.fwd_button.pack()

    def print_label(self):
        print (self.label1['text'])

class subframe_newscripts():
    def __init__(self, parent):
        self = tk.Frame(parent)
        self.pack()
        self.Main_Title = tk.Label(self, text="New Scripts")
        self.Main_Title.grid(row=0, column=0)
        self.Book_display_frame = tk.Frame(self)
        self.Book_display_frame.grid(row=1, column=0)


def books_display(widget):
        print (widget['text'])

app = Window()
subframe = subframe_newscripts(app)

app.mainloop()

我试图用按钮打印标签“ Main_title”。 当我运行程序时,出现此错误:

AttributeError:“ subframe_newscripts”对象没有属性 'Main_Title'

不确定我在做什么错...

1 个答案:

答案 0 :(得分:1)

您的问题归因于此行:

self = tk.Frame(parent)

self用于引用类,这就是我们能够从其他方法以及类外部访问方法和类属性的方式。但是,您实际上是在重新定义要成为框架的自身,而框架没有类属性Main_Title

要更正此问题,您还希望将Frame定义为类属性。这样的事情会很好地工作:

self.frame = tk.Frame(parent)

所有这些都说我会改变一些事情。

  1. 我将编写第二个类以从frame继承。我发现它更干净,更易于维护。

  2. 您应该尝试遵循标准的命名约定。您的命名不一致。您应该花一些时间阅读PEP8,以便您的代码更易于阅读。

  3. 相对于super().__init__(),我更喜欢使用tk.Tk.__init__(),因为它适用于大多数情况以及Python 3的当前标准。

  4. 当您的类是诸如Frame之类的容器时,它更喜欢在类之外应用几何管理器。这样,如果您需要在其他地方使用同一框架,则可以使用任何几何图形管理器而不会在代码的不同区域中使用grid()pack()时发生冲突。

更正并清理代码以更严格地遵循PEP8标准:

import tkinter as tk


class Window(tk.Tk):
    def __init__(self):
        super().__init__()
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand = True)
        self.label1 = tk.Label(container, text="label")
        self.label1.pack()
        tk.Button(self, text="Continue", command=lambda: books_display(sub_frame.main_title)).pack()

    def print_label(self):
        print(self.label1['text'])


class SubFrameNewScripts(tk.Frame):
    def __init__(self, master):
        super().__init__(master)
        self.main_title = tk.Label(self, text="New Scripts")
        self.main_title.grid(row=0, column=0)
        self.book_display_frame = tk.Frame(self)
        self.book_display_frame.grid(row=1, column=0)


def books_display(widget):
    print(widget['text'])


if __name__ == '__main__':
    app = Window()
    sub_frame = SubFrameNewScripts(app)
    sub_frame.pack()
    app.mainloop()

结果:

enter image description here

相关问题