【发布时间】:2021-08-02 02:26:20
【问题描述】:
用户单击按钮后,我想创建一个带有建议的新 TopLevel 窗口,当用户在顶级窗口上选择他/她的建议并单击“完成”按钮时,我想销毁顶级窗口并传递选择的结果到根窗口。这是我想要实现的目标,但直到现在我都无法正确地做到这一点。
我尝试在顶层窗口上使用wait_window,但每次都不起作用,因为有时它不会返回任何内容或无限期冻结。
import tkinter as tk
root = None
BTN = None
listbox = None
selected = None
SUGGESTIONS = [(0, "level 1"), (11, "level 2"), (23, "level 3")]
def select():
global listbox, SUGGESTIONS, selected
selected = listbox.get(tk.ANCHOR)
for (idd, info) in SUGGESTIONS:
if selected == f_info:
selected = idd
def show_suggestions():
global SUGGESTIONS, listbox
win = tk.TopLevel()
win.title("Select suggestion")
win.geometry("400x400")
listbox = tk.Listbox(win, height=20, width=40)
listbox.pack(pady=15)
self.btn = tk.Button(win, text="Confirm selection", command=select)
self.btn.pack(pady=10)
for (idd, info) in SUGGESTIONS :
self.listbox.insert(tk.END, f_info)
#TODO: wait for selected suggestion and assign it to global variable selected
def main():
global root, BTN
root = tk.Tk()
root.title("Youtube to MP3")
root.geometry("575x475")
BTN = tk.Button(
master=root,
text="List suggestions",
width=25,
height=5,
command=show_suggestions
)
BTN.pack(pady=15)
root.mainloop()
【问题讨论】:
-
这不是最好的主意,但您可以使用
<tk.Toplevel>.mainloop(1)来处理所有事件,直到只剩下 1 个窗口。如果要确保用户在顶层运行时不输入任何数据,可以使用全局变量作为标志。 -
wait_window是正确的答案。它应该可靠地工作。如果不是,那么您的代码可能有问题。
标签: python user-interface tkinter