python - 按下另一个按钮后禁用和取消选择单选按钮
问题描述
我正在使用 Python 编写一个简单的数字系统转换器,并且我正在使用 Tkinter 作为 GUI。我试图让它像这样工作:
- 用户按下“发件人:”一侧的“十进制”单选,“收件人:”一侧的“十进制”单选被禁用
- 用户在“To:”侧按下“Octal”,没有任何变化
- 用户在“From:”侧按下“Octal”,“To:”侧的“Octal”单选被禁用并取消选择
但到目前为止,它的工作原理是这样的:
- 用户按下“发件人:”一侧的“十进制”单选,“收件人:”一侧的“十进制”单选被禁用
- 用户在“To:”侧按下“Octal”,没有任何变化
- 用户在“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()
解决方案
您需要清除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)
推荐阅读
- javascript - 使用 JS 将 webp 转换为 jpeg
- angular - Angular 9 为步进器组件设置动画
- email - 端口 587 上的 GMail SMTP STARTTLS 不再有效
- rust - 使用谓词返回引用时的生命周期冲突(使用谓词实现“split at mut”)
- javascript - Javascript / p5.js 中的独立随机生成
- sql - 从 PostgreSQL 函数返回复合类型或多列
- c# - 在 FakeItEasy 测试期间访问属性的运行时值
- python - 轴标签间距不正确
- java - DDD 中域对象集合的最佳实践
- javascript - Antenna House 6.6 是否支持 HTML DOM classList 切换?