我不仅尝试打印单选按钮的值,而且还打印名称。 这样我就可以做到“您选择了值为'23'的'Radio 2'”
from tkinter import *
class Gui:
def __init__(self, master):
self.master = master
self.var = StringVar()
self.var.set("Cat")
radio1 = Radiobutton(self.master, variable=self.var, text="radio1", value="Cat")
radio1.bind('<Double-1>', lambda :self.show_radioname("radio1"))
radio1.pack()
radio2 = Radiobutton(self.master, variable=self.var, text="radio2", value="Dog")
radio2.bind('<Double-1>', lambda :self.show_radioname("radio2"))
radio2.pack()
radio3 = Radiobutton(self.master, variable=self.var, text="radio3", value="Horse")
radio3.bind('<Double-1>', lambda :self.show_radioname("radio3"))
radio3.pack()
submit_button = Button(self.master, text="print", command=self.show_var)
submit_button.pack()
def show_var(self):
print(self.var.get())
@staticmethod
def show_radioname(radio_name):
print(radio_name)
我可以获得电台的价值,但无法获取其文本名称
答案 0 :(得分:1)
使用bind
创建绑定时,Tkinter会自动添加包含有关事件信息的参数。您必须小心考虑这个额外的参数。 (请参阅this answer)
因此,如果您使用的是lambda
,则可以向其添加一个参数,如下所示:
lambda event: self.show_radioname("radio1"))
from tkinter import *
class Gui:
def __init__(self, master):
self.master = master
self.var = StringVar()
self.var.set("Cat")
radio1 = Radiobutton(self.master, variable=self.var, text="radio1", value="Cat")
radio1.bind('<Double-1>', lambda event: self.show_radioname("radio1"))
radio1.pack()
radio2 = Radiobutton(self.master, variable=self.var, text="radio2", value="Dog")
radio2.bind('<Double-1>', lambda event: self.show_radioname("radio2"))
radio2.pack()
radio3 = Radiobutton(self.master, variable=self.var, text="radio3", value="Horse")
radio3.bind('<Double-1>', lambda event: self.show_radioname("radio3"))
radio3.pack()
submit_button = Button(self.master, text="print", command=self.show_var)
submit_button.pack()
self.master.mainloop()
def show_var(self):
print(self.var.get())
@staticmethod
def show_radioname(radio_name):
print(radio_name)
Gui(Tk())