首页 > 解决方案 > 如何访问其他类中的对象

问题描述

我需要buttonReturn从另一个类访问一个对象,Return以便可以调用它的方法。

我想buttonReturn通过将其置于视图之外()来隐藏第一页x=-100,然后使用下一页按钮将返回按钮置于视图中。

我尝试使用Return.buttonReturn.place(x=0, y=0),但它给了我AttributeError: type object 'Return' has no attribute 'buttonReturn'

以下是我可以减少的程序

import tkinter as tk
PreviousPage = None


class Controller(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}

        for F in (FirstPage, SecondPage, Return):
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")

        self.geometry("200x100")
        self.show_frame(FirstPage)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()


class Return(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        buttonReturn = tk.Button(text="return", command=lambda: controller.show_frame(PreviousPage))
        buttonReturn.place(x=-100, y=0)


class FirstPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        label = tk.Label(self, text="first page")
        label.place(x=0, y=50)

        buttonA = tk.Button(self, text="next page", command=lambda: nextPage())
        buttonA.place(x=70, y=0)

        def nextPage():
            global PreviousPage
            PreviousPage = FirstPage
            Return.buttonReturn.place(x=0, y=0) #problematic code
            controller.show_frame(SecondPage)


class SecondPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        label = tk.Label(self, text="second page")
        label.place(x=0, y=50)


app = Controller()
app.mainloop()

标签: python-3.xtkinter

解决方案


您没有创建要调用的 Return 对象,因此您只是在调用该类。为了得到你想要发生的改变:

Return.buttonReturn.place(x=0, y=0)

returnbutton = Return(parent, controller)
returnbutton.buttonReturn.place(x=0, y=0)

并在 Return 类中在 buttonReturn 语句前添加 self :

self.buttonReturn = tk.Button(text="return", command=lambda: controller.show_frame(PreviousPage))
self.buttonReturn.place(x=-100, y=0)

推荐阅读