[英]How to disable and destroy multiple buttons in tkinter?
我目前面臨兩個問題。
當我單擊“邁克”按鈕和邁克的所有子按鈕時,我希望禁用前一行按鈕而不是“薩拉”按鈕
當我單擊“Sara”按鈕時,我希望 Mike 的子按鈕被銷毀並恢復到原始狀態。
很難將我的頭腦圍繞在功能上。 我覺得我在走很長的路。 任何幫助,將不勝感激!
import tkinter as tk
app = tk.Tk()
app.geometry("300x300")
def buttonA1State():
if (buttonA1['state'] == tk.NORMAL):
buttonA1['state'] = tk.DISABLED
else:
buttonA1['state'] = tk.NORMAL
def btn3():
buttonA2 = tk.Button(app, text="Button A2",command = lambda:[buttonA1State(), btn5()])
buttonA2.grid(padx=10, pady=10, row=2, column=1)
buttonA3 = tk.Button(app, text="Button A3",command=btn4)
buttonA3.grid(padx=10, pady=10, row=2, column=2)
def btn4():
buttonA4 = tk.Button(app, text="Button A4")
buttonA4.grid(padx=10, pady=10, row=3, column=2)
def btn5():
buttonA5 = tk.Button(app, text="Button A5")
buttonA5.grid(padx=10, pady=10, row=3, column=1)
buttonA1 = tk.Button(app, text="Mike", command = lambda:[buttonA1State(), btn3()])
buttonA1.grid(padx=10, pady=10, row=1, column=1)
buttonB1 = tk.Button(app, text="Sara", command = btn3 )
buttonB1.grid(padx=10, pady=10, row=1, column=2)
app.mainloop()
names = [["Mike", "Sara"]]
buttons = []
for x in range(names):
buttons.append()
for y in range(names[x]):
buttons[x].append(Button(app, text=names[x][y])))
上面的代碼將允許您使用易於理解的矩陣來引用您的按鈕,您必須稍微調整一下,因為您在第 1 行啟動按鈕,但這很容易完成。 您需要一個全局值來跟上活動的行和列。
class APerson:
def __init__(self, window, name):
self.name = name
self.selected = False
self.select_button = Button(window, text=self.name command=select)
self.secondary_button = Button(window, text="Secondary")
self.another_button = Button(window, text="More Buttons")
def toggle_select(self):
self.selected = not self.selected
mike = APerson(app, "Mike")
sara = APerson(app, "Sara")
def main_callback:
if mike.selected:
etc...
app.after(1000, main_callback)
這些是您可能會發現有用的摘要。 在 Python 和一般編程中,有很多方法可以做事,所以你真的必須選擇對你試圖解決的問題最有意義的方法。 您可能更喜歡創建傳遞按鈕的行對象,而不是具有按鈕的人員對象。 我會避免對每個動作進行硬編碼,特別是如果你需要你的程序擴展的話。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.