Why do Tkinter's Radio Buttons all Start Selected When Using StringVar but not IntVar?

前端 未结 1 886
旧时难觅i
旧时难觅i 2020-12-30 09:07

Here is some example code that creates 4 radio buttons, 2 using int and 2 using str :

from tkinter import *

class test:
    def __init__(self):
        wind         


        
相关标签:
1条回答
  • 2020-12-30 09:36

    In the case of the second set of radiobuttons, they are being rendered in "tri-state mode".

    According to the official documentation1:

    If the variable's value matches the tristateValue, then the radiobutton is drawn using the tri-state mode. This mode is used to indicate mixed or multiple values.

    Explanation

    The default for tristatevalue is the empty string, and the default value for a StringVar is the empty string. For your second set of radiobuttons both the variable value and the tristatevalue are the same so you are seeing the "tri-state mode".

    In the case of the IntVar, the default value of the variable is zero. The tristatevalue is still the empty string. Those two are different so the widget does not appear in "tri-state mode".

    To prove this, set tristatevalue to zero for the first set of radiobuttons so that it matches the default value of the associated variable and you will see that their appearance changes to match the second set.

    int1 = Radiobutton(..., tristatevalue=0)
    int2 = Radiobutton(..., tristatevalue=0)
    

    Likewise, you could set the tristatevalue of the second set to something other than the default value so that they will look like the first set:

    str1 = Radiobutton(..., tristatevalue="x")
    str2 = Radiobutton(..., tristatevalue="x")
    

    Solution

    The best practice with radiobuttons is to always make sure the default value corresponds to one of the radiobutton values, unless you truly do want "tri-state mode".

    In your case, you should initialize the variables to the value of one of the radiobuttons:

    self.v1 = IntVar(value=1)
    self.v2 = StringVar(value="1")
    

    ... or after you create them, via set:

    self.v1.set(1)
    self.v2.set("1")
    

    1 the link goes to the tcl/tk man pages. Tkinter is just a thin wrapper around tcl/tk, and this documentation is the definitive answer to how the widgets behave.

    0 讨论(0)
提交回复
热议问题