Python Tkinter GUI自动关闭,尽管使用了与其他用户类似的结构

Python Tkinter GUI自动关闭,尽管使用了与其他用户类似的结构,python,tkinter,tk,Python,Tkinter,Tk,我使用问题作为如何构造Tkinter类的参考,但是当我运行程序并回答我创建的弹出对话框时,根窗口会自动关闭 from tkinter import * from tkinter import simpledialog as sd from datetime import datetime, date import time import pyowm as owm # access API key owm = foo COUNTRY = 'US' class App(Tk): def

我使用问题作为如何构造Tkinter类的参考,但是当我运行程序并回答我创建的弹出对话框时,根窗口会自动关闭

from tkinter import *
from tkinter import simpledialog as sd 
from datetime import datetime, date
import time
import pyowm as owm

# access API key
owm = foo
COUNTRY = 'US'

class App(Tk):
    def __init__(self):
        # create window and set size
        self.root = Tk()
        self.root.title("Weatherman")
        self.root.geometry('700x200')

        # get location
        self.location = sd.askstring("Input","What's your location? Format as City, Country",parent=self.root)
        self.location.strip()

        # get date and time 
        current_date = StringVar()
        current_date.set(date.today)

        # debug label to check variable
        self.test_label = Label(self.root,text=current_date.get())
        self.test_label.pack()

def main():
    app = App()
    app.mainloop

if __name__ == '__main__':
    main()

如注释中所述,您在任何时候都只能运行一个
tk.tk()
实例。
你需要决定你的应用程序是从
tk.tk
继承,还是由
tk.tk()
的根实例组成

此外,从
\uuuu init\uuuu
方法请求用户输入在某种程度上是一种反模式。我在一个单独的函数中重构了它

最后,当您将
tk.Stringvar
分配给小部件
textvariable
时,它的自驱动能力会得到充分的表达

下面的示例使用了来自
tk.tk
的继承:

import tkinter as tk
from tkinter import simpledialog
from datetime import date


class App(tk.Tk):
    def __init__(self, location=None):
        super().__init__()
        self.title("Weatherman")
        self.geometry('700x200')
        current_date = tk.StringVar()
        current_date.set(str(date.today()))
        self.location = None

        self.test_label = tk.Label(self, textvariable=current_date)
        self.test_label.pack()


def get_location(app):
    location = tk.simpledialog.askstring("Input","What's your location? Format as City, Country")
    return location.strip()


def main():
    app = App()
    app.location = get_location(app)
    app.mainloop()


if __name__ == '__main__':
    main()
阅读