Python 3.x 如何在root.mainloop()之后从选定的单选按钮检索值?
我想写一个弹出窗口,要求用户选择一个特定的选项,如果该选项不存在,添加它。但是,我在检索所选选项的值时遇到问题,即从dict中检索键。我的代码-摘要-到目前为止:Python 3.x 如何在root.mainloop()之后从选定的单选按钮检索值?,python-3.x,tkinter,Python 3.x,Tkinter,我想写一个弹出窗口,要求用户选择一个特定的选项,如果该选项不存在,添加它。但是,我在检索所选选项的值时遇到问题,即从dict中检索键。我的代码-摘要-到目前为止: import tkinter as tk class Category(): def __init__(self): self.categories = {1:"Coffee",2: "Tesco"} def index(...): # code ... # r
import tkinter as tk
class Category():
def __init__(self):
self.categories = {1:"Coffee",2: "Tesco"}
def index(...):
# code ... #
root = tk.Tk()
v = tk.IntVar()
# I was thinking this would help:
def quit():
global irow
irow = v.get()
print("Irow is",irow)
root.quit()
tk.Label(root, text="Choose category:").pack()
for key, cat in self.categories.items():
tk.Radiobutton(root, text=cat, variable=v, value=key).pack()
tk.Radiobutton(root, text="Other", variable=v, value=key+1).pack()
# I want to add a text box here so user can add the "Other"
tk.Button(root, text="Close", command=quit)
irow = v.get()
print(irow)
root.mainloop()
print(irow)
# code which uses irow #
执行此代码将产生:
0
Irow is 0
0
不管我选择什么按钮。我希望irow是2,如果我选择了乐购,我会选择1,如果我选择了咖啡,我会选择3,如果我选择了其他。非常感谢您的指导。通常,mainloop只有在所有小部件都被销毁后才会退出。因此,此时无法直接从小部件获取值。最简单的解决方案是将值保存到全局变量,如果使用类,则保存到实例变量
例如,在您的情况下,您可以这样做:
def quit():
self.irow = v.get()
root.quit()
然后,在mainloop存在之后,您可以访问self.irow
感谢布莱恩·奥克利的回答。我做了4个更改,使它在Linux终端上运行:1我将类从Tk更改为Toplevel; 2为了清洁起见,我把对话放在课堂上;3我将self.quit改为self.destroy;&4我将主循环更改为等待窗口
class AddCategory(tk.Toplevel):
def __init__(self, parent):
tk.Toplevel.__init__(self)
self.v = tk.IntVar()
self.parent = parent
tk.Label(self, text="Choose category:").pack()
for key, cat in self.parent.categories.items():
tk.Radiobutton(self, text=cat, variable=self.v, value=key).pack()
tk.Radiobutton(self, text="Other", variable=self.v, value=key+1).pack()
self.e = tk.Entry(self,text="")
self.e.pack()
tk.Button(self, text="Close", command=self.quit).pack()
def quit(self):
self.parent.key = self.v.get()
self.parent.cat = self.e.get()
print(self.v.get())
print(self.e.get())
self.destroy()
请注意,父类是我从中执行AddCategory对话框的类。我援引它如下:
class Category():
def __init__(self):
self.cat = self.key = self.desc = []
self.categories = {1:"Coffee",2: "Tesco"}
self.descriptions = {}
def index(...):
# code ... #
dialog = AddCategory(self) # I pass the parent onto the dialog
dialog.wait_window()
print(self.key)
print(self.cat)
这是因为AddCategory中的self.parent是parent的软拷贝。谢谢。这是可行的,但在我做出选择后,值v仍然没有得到更新。也就是说,它保持为默认值0。你知道为什么吗?@埃里克:我不知道。当我修复代码中的错误时,它正确地打印了我在单击“关闭”按钮后选择的项目。这似乎证明它确实在更新。很有趣。Idle确实会在不关闭对话框的情况下向我显示正确的键,而终端会关闭对话框,但不会给我正确的键。
class Category():
def __init__(self):
self.cat = self.key = self.desc = []
self.categories = {1:"Coffee",2: "Tesco"}
self.descriptions = {}
def index(...):
# code ... #
dialog = AddCategory(self) # I pass the parent onto the dialog
dialog.wait_window()
print(self.key)
print(self.cat)