【问题标题】:Python Get the Selected Radio Button's Text/label Name and not just the ValuePython获取选定单选按钮的文本/标签名称,而不仅仅是值
【发布时间】:2019-05-03 07:55:58
【问题描述】:

我不仅要打印单选按钮的值,还要打印它的名称。 这样我就可以做到这一点“您选择了值为 '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)

我可以得到 The Radio 的值但无法得到它们的文本名称

【问题讨论】:

    标签: python-3.x tkinter radio-button


    【解决方案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())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-26
      • 2017-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多