首页 文章

Radiobuttons正在修改错误的值tkinter

提问于
浏览
0

我正在使用tkinter编写脚本,但发生了一些奇怪的事情 .

我有两个radioButtons:

way=False
RadioButton0=Radiobutton(root,text="From",variable=way,value=False)
RadioButton1=Radiobutton(root,text="To",variable=way,value=True)
RadioButton0.grid(column=0,row=2)
RadioButton1.grid(column=1,row=2)

和文本输入字段:

entryValue=0
entryField=Entry(root,textvariable=entryValue)
entryField.grid(column=0,row=4)

当我在输入字段中输入 0 时,会自动选择 RadioButton0 ,当我输入 1 时,选择了 RadioButton1 ,对于任何其他值,它们都被选中...这反过来:当我选择 RadioButton0 时,输入字段更改为 0 并且当我选择 RadioButton1 时,输入字段更改为 1 ...此外, entryValue 后来被视为 0 . 变量 way 只能通过单选按钮进行修改......

为什么会这样?我在做一些我不应该做的事吗?我该如何解决?

2 回答

  • 3

    您可以使用命令来调用方法并设置值 . 请参阅附件代码 .

    def sel():
       selection = "You selected the option " + str(var.get())
       label.config(text = selection)
    
    
    root = Tk()
    frame = Frame(root)
    frame.pack()
    
    labelframe = LabelFrame(frame, text="This is a LabelFrame")
    labelframe.pack(fill="both", expand="yes")
    
    
    var = IntVar()
    R1 = Radiobutton(labelframe, text="Option 1", variable=var, value=1,
                      command=sel)
    R1.pack( anchor = W )
    
    R2 = Radiobutton(labelframe, text="Option 2", variable=var, value=2,
                      command=sel)
    R2.pack( anchor = W )
    
    R3 = Radiobutton(labelframe, text="Option 3", variable=var, value=3,
                      command=sel)
    R3.pack( anchor = W)
    
    
    label = Label(labelframe)
    label.pack()
    
  • 1

    variabletextvariable 应该是不同的variable objects,而不仅仅是内置数据类型:

    way=BooleanVar(root)
    way.set(False)
    # ...
    entryValue=StringVar(root)
    entryValue.set("0")
    

相关问题