我正在與 Tkinter 合作,我正在嘗試使用一些復選按鈕。
這就是我正在做的事情:
- 獲取一份包含一些成分的清單
- 獲得一個帶有一些復選按鈕的 tkinter GUI(每種成分一個)
- 選擇一些復選按鈕(勾選它們)
- 按下按鈕并獲取包含我選擇的成分的串列
我現在要做的是:
- 按下“確認”按鈕后,使檢查按鈕無法使用(因此,禁用它們)。
我的代碼來自我的另一個問題的已接受答案(我在應用程式的檢查按鈕中沒有取得太大進展)。我在下面報告:
import tkinter as tk
root = tk.Tk()
INGREDIENTS = ['cheese', 'ham', 'pickle', 'mustard', 'lettuce']
txt = tk.Text(root, width=40, height=20)
variables = []
for i in INGREDIENTS:
variables.append( tk.IntVar( value = 0 ) )
cb = tk.Checkbutton( txt, text = i, variable = variables[-1] )
txt.window_create( "end", window=cb )
txt.insert( "end", "\n" )
txt.pack()
def read_ticks():
result = [ ing for ing, cb in zip( INGREDIENTS, variables ) if cb.get()>0 ]
print( result )
but = tk.Button( root, text = 'Read', command = read_ticks)
but.pack()
root.mainloop()
先感謝您。
uj5u.com熱心網友回復:
下面的解決方案基于記住對串列中的復選按鈕的參考,但也應該可以通過查詢 root 的所有子項來獲取這些參考,不包括 tk.Button 被禁用。
import tkinter as tk
root = tk.Tk()
INGREDIENTS = ['cheese', 'ham', 'pickle', 'mustard', 'lettuce']
txt = tk.Text(root, width=40, height=20)
variables = []
buttons = []
for i in INGREDIENTS:
variables.append( tk.IntVar( value = 0 ) )
cb = tk.Checkbutton( txt, text = i, variable = variables[-1] )
buttons.append(cb)
txt.window_create( "end", window=cb )
txt.insert( "end", "\n" )
txt.pack()
def read_ticks():
result = [ ing for ing, cb in zip( INGREDIENTS, variables ) if cb.get()>0 ]
print( result )
for button in buttons:
button.config(state = 'disabled')
but = tk.Button( root, text = 'Read', command = read_ticks)
but.pack()
root.mainloop()
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/492755.html
