我希望我的tkinter应用程序将列表框的选定项从被调用的窗口(类 MyDialog )返回到调用窗口(类示例)。如果我不使用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()
答案 0 :(得分:1)
wait_window
等待寡妇被摧毁。而且由于它被销毁,你无法从小部件中提取任何信息。
您必须设置绑定,以便在数据更改时将数据保存到变量,以便您可以在销毁窗口小部件后获取它。
答案 1 :(得分:0)
Bryan Oakley的回答让我得到了下面发布的解决方案。非常感谢你!
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()
# add binding
self.listbox.bind('<<ListboxSelect>>', self.getSelection)
# function associated with binding
def getSelection(self, event):
widget = event.widget
selection=widget.curselection()
self.value = widget.get(selection[0])
# separate function for wait_window and the return of the selection
def returnValue(self):
self.toplevel.wait_window()
return self.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).returnValue()
self.label.configure(text="your result: %s" % result)
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(fill="both", expand=True)
root.mainloop()