【问题标题】:Disabling and deselecting radio button after another is pressed按下另一个按钮后禁用和取消选择单选按钮
【发布时间】:2020-11-13 10:54:02
【问题描述】:

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

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

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

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

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

我的代码:

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()

【问题讨论】:

  • 我知道这不是一个功能示例,但我仍在努力,我被困在单选按钮部分。

标签: python python-3.x tkinter


【解决方案1】:

如果“from”和“to”都相同,则需要清除tosel

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)

【讨论】:

  • 非常感谢!这实际上完全按照预期工作:D
猜你喜欢
  • 2019-03-25
  • 2011-11-05
  • 2015-02-27
  • 2020-05-21
  • 1970-01-01
  • 1970-01-01
  • 2011-03-16
  • 2020-10-21
  • 1970-01-01
相关资源
最近更新 更多