简体   繁体   English

Python tkinter RadioButton回调函数

[英]Python tkinter RadioButton callback function

This comes from a button that when pressed generates a radiobutton. 这来自一个按钮,按下该按钮会生成一个单选按钮。 I am not able to access to the choice made with radiobutton. 我无法使用单选按钮进行选择。 Everything works fine, but the output of selected function is zero. 一切正常,但是所选函数的输出为零。 I try using both local and global var but the result is the same. 我尝试同时使用本地和全局var,但结果是相同的。

def callback_st(): # RadioButton select technology
    var = IntVar()
    m=0
    for m in range(len(un_tech)):
        Radiobutton(radio_frame, text=un_tech[m], value=m, variable=var,
                    command=selected(var)).pack(anchor=W)

def selected(var):
    print(var)

This doesn't work. 这行不通。 I solved using lambda: 我解决了使用lambda:

    def selected(jst):
        global sel_technology
        sel_technology=un_tech[jst]
        print(sel_technology)

def callback_st(): #RadioButton select technology
    var_st = IntVar()
    m=0
    for m in range(len(un_tech)):
    Radiobutton(radio_frame, text=un_tech[m], value=m, variable=var_st,
                command = lambda jst=m: selected(jst)).pack(anchor=W)

This works as i want, but it isn't the solution that i want and i think is not the correct way. 这可以按我想要的方式工作,但这不是我想要的解决方案,我认为这不是正确的方法。 So, somebody can help me to find the right way? 那么,有人可以帮助我找到正确的方法吗?

In your first try, you call selected immediately, when var has a value of 0 . 在第一次尝试中,当var的值为0时,您立即调用 selected You avoided this with the lambda expression, but you are correct that this is an awkward workaround for the original mistake. 您使用lambda表达式避免了这种情况,但是您正确地认为这对于原始错误而言是一个尴尬的解决方法。 Make var global and have selected access it as a global. var设为global,并selected其作为全局selected访问。 Modifying your first code: 修改您的第一个代码:

var = IntVar()
def selected():
    print(var.get())
def callback_st():
    ...
         ...command=selected...

If you were defining a class and methods, var would be an instance attribute instead of global. 如果要定义类和方法,则var将是实例属性,而不是全局属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM