【问题标题】:Tkinter - How can I open a window by clicking a button?Tkinter - 如何通过单击按钮打开窗口?
【发布时间】:2015-09-07 08:47:01
【问题描述】:

在尝试使用 EasyGUI 制作游戏后,我发现它不会做一些对游戏很重要的事情,所以我开始使用 Tkinter。但是我遇到了另一个我不知道如何解决的问题。代码如下:

money = Button(box2, text = "Get Money", highlightbackground = "yellow", command = close_parentg)

def moneywindow():
    parent.destroy() # The button is inside the parent.
    Money.mainloop() # This is the window I want to open.

destroy() 命令工作正常,因为当我按下按钮时第一个窗口关闭,但如果我运行程序,第二个窗口会弹出,即使我没有告诉它(或者我至少认为我没有)。

如何阻止第二个窗口在开始时弹出并仅在我单击按钮时显示?

【问题讨论】:

  • 您需要显示更多的代码,您能否提供一个minimal reproducible example 来重现您的问题?
  • 如果我运行程序是什么意思?程序不是已经运行了吗?

标签: python tkinter


【解决方案1】:

mainloop() 不是创建窗口的原因。创建窗口的唯一两种方式是在程序开始时创建Tk 的实例,以及在程序运行时创建Toplevel 的实例。

您的 GUI 应该只调用一次 mainloop(),并且应该在应用程序的整个生命周期内保持运行。当你销毁根窗口时它会退出,而 tkinter 的设计是当你销毁根窗口时程序退出。

一旦你这样做了,除非你用Toplevel 明确地创建它们,否则不会弹出任何窗口。

这是一个示例,它允许您创建多个窗口,并使用lambda 为每个窗口提供一个可自行销毁的按钮。

import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        new_win_button = tk.Button(self, text="Create new window", 
                                   command=self.new_window)
        new_win_button.pack(side="top", padx=20, pady=20)

    def new_window(self):
        top = tk.Toplevel(self)
        label = tk.Label(top, text="Hello, world")
        b = tk.Button(top, text="Destroy me", 
                      command=lambda win=top: win.destroy())
        label.pack(side="top", fill="both", expand=True, padx=20, pady=20)
        b.pack(side="bottom")

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

【讨论】:

    猜你喜欢
    • 2013-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-03
    • 2015-09-09
    • 2023-03-07
    相关资源
    最近更新 更多