gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 05:30:50 24 4
gpt4 key购买 nike

我希望我的 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),以便在数据发生变化时将数据保存到变量中,以便您可以在小部件被销毁后获取它。

关于python - 在 tkinter 中使用 wait_window() 时如何返回列表框的选定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37219191/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com