【问题标题】:Hiding Label from on one Class by pressing a Button in another Class通过按下另一个类中的按钮来隐藏一个类中的标签
【发布时间】:2020-01-23 22:28:34
【问题描述】:

我有一个想法来创建一个带有两个窗口的简单记分牌应用程序(运动)(在 Tkinter 中创建)。一个用于控制,另一个用于输出信息。

所以我的想法是我在 tk.Toplevel 窗口中按下“显示记分牌”​​按钮,它会出现在主应用程序窗口中。当我按下隐藏时,它会隐藏。我知道我可以只编写没有类的脚本来创建它,就像数百个 def 字符串一样,但我想使用 OOP,因为我想以正确的方式开始编程。

我的问题是,当我按下“隐藏记分牌”(我为记分牌创建标签)时,标签没有隐藏。有什么建议吗?

我知道command和defs必须在同一个“树”,但是在使用OOP的时候如何安排呢。

这是我的代码

import tkinter as tk

def forget():
scoreboard.pack_forget()

class Main(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("Scorebug")
        self.geometry("500x300")
        self.configure(background="green")
        scoreboard = tk.Label(self, text="This is like scoreboard")
        scoreboard.pack()

class Control(tk.Toplevel):
    def __init__(self):
        super().__init__()
        self.title("Controls")
        self.geometry("100x300")
        self.configure(background="red")

        hidelabels = tk.Button(self, text="Hide the scoreboard", command=forget)
        hidelabels.pack()


app = Main()
ctr = Control()

ctr.mainloop()
app.mainloop()

【问题讨论】:

  • 一个很好的学习方法是如何使用调试器,这里调试器的好答案,stackoverflow.com/questions/4929251/…。作为第一步,看看您是否可以使用调试器来检查行 hidelabels = tk.Button ... 在您运行代码时实际被调用
  • tkinter 应该只运行一个mainloop()
  • 您的 scoreboard 是局部变量,仅在 Python 运行 __Init__ 时存在,但后来它会删除此变量。您应该使用self. 来保持对self.scoreboard. 的访问权限 您可以将主窗口作为参数发送到第二个窗口 - Control(app) 然后您就可以访问主窗口了,

标签: python python-3.x class tkinter


【解决方案1】:

首先您应该使用self.scoreboard 从其他地方访问。

self.scoreboard = tk.Label(self, text="This is like scoreboard")
self.scoreboard.pack()

现在您可以使用删除它

command=app.scoreboard.pack_forget

您也可以将主窗口作为参数发送到第二个窗口

ctr = Control(app)

class Control(tk.Toplevel):
    def __init__(self, parent):

然后就可以绑定了

command=parent.scoreboard.pack_forget

import tkinter as tk

class Main(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("Scorebug")
        self.geometry("500x300")
        self.configure(background="green")
        self.scoreboard = tk.Label(self, text="This is like scoreboard")
        self.scoreboard.pack()

class Control(tk.Toplevel):
    def __init__(self, parent):
        super().__init__()
        self.title("Controls")
        self.geometry("100x300")
        self.configure(background="red")

        hidelabels = tk.Button(self, text="Hide the scoreboard", command=parent.scoreboard.pack_forget)
        hidelabels.pack()


app = Main()
ctr = Control(app)
app.mainloop()

编辑:您也可以仅将 scireboard 作为参数发送到第二个窗口

ctr = Control(app.scoreboard)

然后就可以绑定了

command=parent.pack_forget

【讨论】:

  • 非常感谢,这正是我所需要的。我打破了我的头,试图找出我做错了什么。我正在学习python一个月左右,我是新手。
猜你喜欢
  • 2014-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-20
  • 1970-01-01
  • 2011-12-10
相关资源
最近更新 更多