我是 tkinter 的初學者,遇到了麻煩。我想要一個單選按鈕組,它可以啟用或禁用某些按鈕、刻度等,以選擇哪個單選按鈕。這些按鈕組連接到一個變數。要禁用/啟用小部件,我使用按鈕組命令。當我單擊單選按鈕時,一切正常。但是如果變數改變了,單選按鈕改變了,沒有呼叫radio命令,所以其他小部件不會更新。
這是我想做的一個非常簡單的代碼
from tkinter import ttk
import tkinter as tk
root = tk.Tk()
frame = ttk.LabelFrame(root, text='choice your futur')
frame.pack(fill="both", expand="yes", padx=5, pady=5)
selection = tk.IntVar()
def onButtonClic():
selection.set(1)
bt = tk.Button(frame, text='continue', command=onButtonClic)
bt.grid(column=0, row=1, columnspan=2, sticky='ew')
def onRadioButtonChange():
if selection.get() != 0:
bt.configure(state = tk.DISABLED)
else:
bt.configure(state = tk.NORMAL)
tk.Radiobutton(frame, command=onRadioButtonChange, text = "blue pill", variable = selection, value = 0).grid(column=0, row=0, sticky='nw')
tk.Radiobutton(frame, command=onRadioButtonChange, text = "red pill", variable = selection, value = 1).grid(column=1, row=0, sticky='nw')
root.mainloop()
如果我選擇紅色藥丸,按鈕將被禁用。選擇藍色藥丸后,單擊按鈕(將單選變數設定為 1:紅色藥丸值),紅色藥丸被選中,但按鈕仍處于啟用狀態。我想當變數改變時,呼叫無線電命令。
最好的問候 JM
uj5u.com熱心網友回復:
您可以改用 tkinter 變數.trace_add()函式:
...
def onRadioButtonChange(*args):
if selection.get() != 0:
bt.configure(state = tk.DISABLED)
else:
bt.configure(state = tk.NORMAL)
# call onRadioButtonChange() when the variable is updated
selection.trace_add('write', onRadioButtonChange)
tk.Radiobutton(frame, text = "blue pill", variable = selection, value = 0).grid(column=0, row=0, sticky='nw')
tk.Radiobutton(frame, text = "red pill", variable = selection, value = 1).grid(column=1, row=0, sticky='nw')
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/425923.html
標籤:python-3.x tkinter 事件 单选按钮
