tkinter 单选按钮不更新变量 [英] tkinter radiobutton not updating variable

查看:47
本文介绍了tkinter 单选按钮不更新变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

--更新:我改了

variable=self.optionVal.get()

variable=self.optionVal

但没有任何改变.另外我想知道为什么它在编译时自动调用 self.selected?

But nothing changed.Also I wonder why it automatically call self.selected while compiling?

----原文:

我正在尝试熟悉单选按钮,但我认为我不了解单选按钮的工作原理.下面是一段简短的演示代码:

I'm trying to get familiar with radiobutton, but I don't think I understand how radiobutton works. Here's a brief code for demonstration:

     self.optionVal = StringVar()
     for text, val in OPTIONS:
         print(text,val)
         radioButton = Radiobutton(self,
                                   text=text,
                                   value=val,
                                   variable=self.optionVal.get(),
                                   command = self.selected())
        radioButton.pack(anchor=W) 

     def selected(self):
        print("this option is :"+self.optionVal.get())

In my opinion this should work like once I choose certain button, and it prints out "this option is *the value*", however now what it does is once compiled, it prints out everything, and the self.optionVal.get() is blankspace, as if value wasn't set to that variable.

I wonder what happens to my code,
Many thanks in advance. 

推荐答案

啊哈!我相信我已经想通了.我有完全相同的问题.确保您将主分配给 IntVar,例如 self.rbv=tk.IntVar(master) #or 'root' 或您正在使用的任何内容):

AHA! I beleive I've figured it out. I had the exact same issue. make sure you are assigning a master to the IntVar like self.rbv=tk.IntVar(master) #or 'root' or whatever you are using):

import Tkinter as tk
import ttk

class My_GUI:

    def __init__(self,master):
        self.master=master
        master.title("TestRadio")

        self.rbv=tk.IntVar(master)#<--- HERE! notice I specify 'master'
        self.rb1=tk.Radiobutton(master,text="Radio1",variable=self.rbv,value=0,indicatoron=False,command=self.onRadioChange)
        self.rb1.pack(side='left')
        self.rb2=tk.Radiobutton(master,text="Radio2",variable=self.rbv,value=1,indicatoron=False,command=self.onRadioChange)
        self.rb2.pack(side='left')
        self.rb3=tk.Radiobutton(master,text="Radio3",variable=self.rbv,value=2,indicatoron=False,command=self.onRadioChange)
        self.rb3.pack(side='left')

    def onRadioChange(self,event=None):
        print self.rbv.get()

root=tk.Tk()
gui=My_GUI(root)
root.mainloop()

尝试运行它,单击不同的按钮(它们是单选按钮,但指标为 false),您将看到它打印正确更改的值!

try running that, click the different buttons (they are radiobuttons but with indicatoron=False) and you will see it prints correctly changed values!

这篇关于tkinter 单选按钮不更新变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆