首页 > 解决方案 > 按下另一个按钮后禁用和取消选择单选按钮

问题描述

我正在使用 Python 编写一个简单的数字系统转换器,并且我正在使用 Tkinter 作为 GUI。我试图让它像这样工作:

  1. 用户按下“发件人:”一侧的“十进制”单选,“收件人:”一侧的“十进制”单选被禁用
  2. 用户在“To:”侧按下“Octal”,没有任何变化
  3. 用户在“From:”侧按下“Octal”,“To:”侧的“Octal”单选被禁用并取消选择

但到目前为止,它的工作原理是这样的:

  1. 用户按下“发件人:”一侧的“十进制”单选,“收件人:”一侧的“十进制”单选被禁用
  2. 用户在“To:”侧按下“Octal”,没有任何变化
  3. 用户在“From:”侧按下“Octal”,“To:”侧的“Octal”单选被禁用但保持选中状态

我应该进行哪些更改才能使其按预期工作?

我的代码:

from tkinter import *

root = Tk()

fromsel = IntVar()
tosel = IntVar()

def disable_button():
    fr = fromsel.get()
    tbin_radio.config(state = DISABLED if fr == 2 else NORMAL)
    toct_radio.config(state = DISABLED if fr == 8 else NORMAL)
    tdec_radio.config(state = DISABLED if fr == 10 else NORMAL)
    thex_radio.config(state = DISABLED if fr == 16 else NORMAL)

fromlabel = Label(root, text="From:", justify = LEFT, anchor = W)

fbin_radio = Radiobutton(root, text="Binary", variable = fromsel, value = 2, command = disable_button)
foct_radio = Radiobutton(root, text="Octal", variable = fromsel, value = 8, command = disable_button)
fdec_radio = Radiobutton(root, text="Decimal", variable = fromsel, value = 10, command = disable_button)
fhex_radio = Radiobutton(root, text="Hexadecimal", variable = fromsel,  value = 16, command = disable_button)

fromentry = Entry(root)

tolabel = Label(root, text="To:")

tbin_radio = Radiobutton(root, text="Binary", variable = tosel, value = 1)
toct_radio = Radiobutton(root, text="Octal", variable = tosel, value = 2)
tdec_radio = Radiobutton(root, text="Decimal", variable = tosel, value = 3)
thex_radio = Radiobutton(root, text="Hexadecimal", variable = tosel,  value = 4)

toentry = Entry(root)

fromlabel.grid(row = 0)

fbin_radio.grid(row = 1, column = 0)
foct_radio.grid(row = 1, column = 1)
fdec_radio.grid(row = 1, column = 2)
fhex_radio.grid(row = 1, column = 3)

fromentry.grid(row = 2, columnspan = 4)

tolabel.grid(row = 3)

tbin_radio.grid(row = 4, column = 0)
toct_radio.grid(row = 4, column = 1)
tdec_radio.grid(row = 4, column = 2)
thex_radio.grid(row = 4, column = 3)

toentry.grid(row = 5, columnspan = 4)

root.mainloop()

标签: pythonpython-3.xtkinter

解决方案


您需要清除tosel“from”和“to”是否相同:

def disable_button():
    fr = fromsel.get()
    tbin_radio.config(state = DISABLED if fr == 2 else NORMAL)
    toct_radio.config(state = DISABLED if fr == 8 else NORMAL)
    tdec_radio.config(state = DISABLED if fr == 10 else NORMAL)
    thex_radio.config(state = DISABLED if fr == 16 else NORMAL)
    mappings = ((2,1), (8,2), (10,3), (16,4))
    if (fr,tosel.get()) in mappings:
        # both "from" and "to" are the same, so clear "to" selection
        tosel.set(None)

推荐阅读