python-3.x - 如何访问其他类中的对象
问题描述
我需要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()
解决方案
您没有创建要调用的 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)
推荐阅读
- ios - Detox:如何使用 detox 在通知中心点击 iOS 推送通知
- javascript - 数字给出意想不到的结果(小数)
- reactjs - 将预先存在的静态 HTML 页面添加到 React/Gatsby 站点的最快方法
- python - Flask 服务器端会话
- c# - 如何在 c# 属性中使用字符串格式?
- python - Python:选择来自多个用户的最新条目的行
- typescript - 基类返回对扩展类类型不匹配的引用
- javascript - 函数在反应JSX中没有返回值
- android - 使用 sharedPreferences 获取 NullPointerException
- html - CSS - 将我的导航栏水平放置