我正在学习tkinter
,并希望在我的项目中使用它,但我一直在思考如何做到这一点。我想知道代码如何返回所选选项
代码如下:
from tkinter import *
from tkinter.ttk import *
master = Tk()
master.geometry("175x200")
v = StringVar(master, "1")
options = {
"RadioButton 1": "1",
"RadioButton 2": "2",
"RadioButton 3": "3",
"RadioButton 4": "4",
"RadioButton 5": "5"
}
for (text, value) in options.items():
Radiobutton(master, text=text, variable=v,
value=value).pack(side=TOP, ipady=5)
print(StringVar())
quit_btn = Button(master, text="Quit", command=master.quit, width=10)
quit_btn.pack()
mainloop()
def selected_opition():
return options.get(text, value)
print(selected_opition())
虽然还有一些小错误,但要点是只在按下按钮后调用
v.get()
。所以你必须把它放在一个函数中,就像我用quitbutton()
函数做的那样。该函数将在单击按钮时立即调用,因为它显示command=quitbutton
另外,您尝试打印
StringVar()
,但不应该这样做。您创建了一个变量v
,它是StringVar。之后,您应该调用该v而不是StringVar。因此,与其做print(StringVar)
,不如做print(v.get())
我还建议您在Youtube上观看一些关于Tkinter的教程,因为这将增强您对基本原理的理解。您的代码非常好,但它缺少一些基础知识,这使得它无法按您希望的方式工作
相关问题 更多 >
编程相关推荐