Skip to main content
 首页 » 编程设计

python之在 tkinter 中使用 wait_window() 时如何返回列表框的选定项

2025年04月02日15mengfanrong

我希望我的 tkinter 应用程序将列表框的选定项目从被调用窗口(MyDialog 类)返回到调用窗口(Example 类)。如果我不使用 wait_window(),将返回一个空列表。使用 wait_window() 会导致错误消息。在我看来 wait_window() 阻止了 curselection() 方法。需要更改什么才能获得正确的返回?

以下示例是 this answer 的修改版本.

import tkinter as tk 
 
class MyDialog(object): 
    def __init__(self, parent): 
        self.toplevel = tk.Toplevel(parent) 
 
        choices = ("one", "two","three") 
        names = tk.StringVar(value=choices) 
 
        label = tk.Label(self.toplevel, text="Pick something:") 
        self.listbox = tk.Listbox(self.toplevel, listvariable=names, height=3, 
            selectmode="single", exportselection=0) 
        button = tk.Button(self.toplevel, text="OK", command=self.toplevel.destroy) 
 
        label.pack(side="top", fill="x") 
        self.listbox.pack(side="top", fill="x") 
        button.pack() 
 
    def show(self): 
        self.toplevel.wait_window() 
 
        value = self.listbox.curselection() 
        return value 
 
class Example(tk.Frame): 
    def __init__(self, parent): 
        tk.Frame.__init__(self, parent) 
 
        self.button = tk.Button(self, text="Click me!", command=self.on_click) 
        self.label = tk.Label(self, width=80) 
        self.label.pack(side="top", fill="x") 
        self.button.pack(pady=20) 
 
    def on_click(self): 
        result = MyDialog(self).show() 
        self.label.configure(text="your result: %s" % result) 
 
if __name__ == "__main__": 
    root = tk.Tk() 
    Example(root).pack(fill="both", expand=True) 
    root.mainloop() 

请您参考如下方法:

wait_window 等待寡妇被销毁。由于它已被销毁,您无法从小部件中提取任何信息。

您必须设置绑定(bind),以便在数据发生变化时将数据保存到变量中,以便您可以在小部件被销毁后获取它。