简单的 Tkinter 程序 - window 在点击按钮后消失 - maintop 问题?

simple Tkinter program - window vanishes after clicking button - maintop problem?

码农们, 我想我有一个新手问题:当我点击一个按钮时,我的 windows 消失了。如果我在 buttonClicked 函数的最后一行输入 root.mainloop(),那么程序没问题 - 但它看起来不对......这里有什么问题?

import tkinter as tk

def buttonClicked(event):
    print(tf1.get())
    tf1Content.set("button clicked")
    # root.mainloop() ... would work

root = tk.Tk()

frame = tk.Frame(root, relief="ridge", borderwidth=2)
frame.pack(fill="both",expand=1)
label = tk.Label(frame, text="Input:")
label.pack(expand=1)
tf1Content = tk.StringVar()
tf1 = tk.Entry(frame, text="input here", textvariable=tf1Content)
tf1.pack(expand=1)
bOk = tk.Button(frame,text="OK",command=root.destroy)
bOk.bind("<Button-1>", buttonClicked)
bOk.widget = "bOK"
bOk.pack(side="bottom")

tf1.focus()

root.mainloop()

原来你只是复制了这一行:

bOk = tk.Button(frame,text="OK",command=root.destroy)

将对 root.destroy() 的调用绑定到按钮按下。

修复方法是删除 command 参数:

bOk = tk.Button(frame,text="OK")