【问题标题】:Window in tkinter automatically closestkinter 中的窗口自动关闭
【发布时间】:2021-06-05 08:15:58
【问题描述】:

我有一些从 tkinter 教程中复制的代码,所以我确信它是 100% 正确的:

import tkinter as tk


class Application(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()
        self.create_widgets()

    def create_widgets(self):
        self.hi_there = tk.Button(self)
        self.hi_there["text"] = "Hello World\n(click me)"
        self.hi_there["command"] = self.say_hi
        self.hi_there.pack(side="top")

        self.quit = tk.Button(self, text="QUIT", fg="red",
                              command=self.master.destroy)
        self.quit.pack(side="bottom")

    def say_hi(self):
        print("hi there, everyone!")


root = tk.Tk()
app = Application(master=root)
app.mainloop()

它应该可以工作,但是当我运行程序时,它会显示窗口大约 1 毫秒,然后立即关闭。我该如何解决这个问题?

我正在使用 Python 3.8。

【问题讨论】:

  • 当我运行它时不会这样做,Button 也可以。
  • 错误不可重现,投票结束问题。
  • @Yatin OP 在已删除的答案/评论中提到了 python 版本。

标签: python tkinter


【解决方案1】:

mainloop() 应该在 tk.Tk 对象上调用,但在您的代码中 apptk.Frame 对象。所以,试试...

root.mainloop()

【讨论】:

  • 没关系 - 无论您调用哪个小部件,主循环的行为都是相同的。
  • mainloop() 是一种通用方法,可以在任何 tkinter 小部件上调用。
猜你喜欢
  • 1970-01-01
  • 2017-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-26
  • 1970-01-01
  • 2010-09-11
相关资源
最近更新 更多