我是 tkinter 的新手。我有一個按鈕 A 串列,當我選擇其中一個按鈕時,我還可以更新標簽(參見代碼)。現在我想要第二個按鈕 B 串列,其中按鈕的數量(和功能)取決于單擊按鈕 A 串列中的按鈕(我試圖在圖片中顯示它)。
我在這里做錯了什么?你能幫我嗎!
import tkinter as tk
root = tk.Tk()
root.title("Analyser")
root.geometry("750x250")
group_number = tk.StringVar()
l0 = tk.Label(root, textvariable=group_number, width=20)
l0.grid(row=1,column=1)
def func(n):
group_number.set("Selected Button: Button " str(n 1))
Buttons_A = ["Button 1","Button 2"]
l2 = tk.Label(root, text = "BUTTONS A",font=('Helvetica', 12, "bold"), fg='white', bg='#107baf', width=20)
l2.grid(row=0, column=0,padx=4,pady=8)
for i in range(len(Buttons_A)):
btn=tk.Button(root, text=Buttons_A[i], font=('Helvetica', 10), bg='#d8e7ea', width=20, activebackground='#42bed8')
btn.config(command=lambda n=i:func(n))
btn.grid(row=i 1,column=0, padx=4,pady=4)
Buttons_B_1 = ["Button 1","Button 2","Button 3"]
Buttons_B_2 = ["Button 1"]
l2 = tk.Label(root, text = "BUTTONS B",font=('Helvetica', 12, "bold"), fg='white', bg='#107baf', width=20)
l2.grid(row=0, column=2,padx=4,pady=8)
for i in range(len(Buttons_B_1)):
btn=tk.Button(root, text=Buttons_B_1[i], font=('Helvetica', 10), bg='#d8e7ea', width=20, activebackground='#42bed8')
btn.config(command=lambda n=i:func(n))
btn.grid(row=i 1,column=2, padx=4,pady=4)
root.mainloop()
當從按鈕串列 A 中選擇按鈕 1 時:

當從按鈕串列 A 中選擇按鈕 2 時:

uj5u.com熱心網友回復:
您應該將按鈕 B 保留在串列中,以便您可以輕松地銷毀它們。
當您單擊按鈕 A 時,它會運行func并在此函式內,您應該從串列中銷毀按鈕,清除此串列,創建新按鈕并將它們添加到此串列中。
如果您將按鈕 B1 和 B2 作為子串列保留在一個串列中,則代碼會更簡單。
最少的作業代碼。
我洗掉了字體和顏色以僅顯示重要元素。
import tkinter as tk
# --- functions ---
def func(n):
group_number.set(f"Selected Button: Button {n 1}")
create_buttons_B(n)
def create_buttons_B(selected_button_1):
# remove previous buttons
for button in existing_buttons_B:
button.destroy()
# clear list
existing_buttons_B.clear()
# create new buttons and add to list
buttons = Buttons_B[selected_button_1]
for number, text in enumerate(buttons):
btn = tk.Button(root, text=text)
btn.grid(row=number 1, column=2)
existing_buttons_B.append(btn)
# --- main ---
Buttons_A = ["Button 1", "Button 2"]
Buttons_B = [
["Button B1 1", "Button B1 2", "Button B1 3"],
["Button B2 1"],
]
existing_buttons_B = [] # list for created buttons B
root = tk.Tk()
group_number = tk.StringVar(root)
l0 = tk.Label(root, textvariable=group_number, width=20)
l0.grid(row=1, column=1)
l2 = tk.Label(root, text="BUTTONS A")
l2.grid(row=0, column=0)
for number, text in enumerate(Buttons_A):
btn = tk.Button(root, text=text, command=lambda n=number:func(n))
btn.grid(row=number 1, column=0)
l2 = tk.Label(root, text="BUTTONS B")
l2.grid(row=0, column=2)
#create_buttons_B(0) # create buttons at start
root.mainloop()
最終,您可以使用Frame對按鈕進行分組,然后您只需要銷毀Frame它,它也會銷毀按鈕。
但是您也可以先創建帶有按鈕的框架并將按鈕放入框架中,然后用于grid_forget()洗掉一個框架并grid()顯示另一個框架。
uj5u.com熱心網友回復:
應用程式中的兩列按鈕(BUTTON A串列中的按鈕和串列中的按鈕BUTTON B)可以組織成兩級層次結構,并且可以輕松地在字典中表示,如下所示:
BUTTON_GROUPS = {
"Group 1": ["Button 1", "Button 2", "Button 3"],
"Group 2": ["Button 1"],
}
上述格式的資料可用于驅動 GUI 其余部分的構建。由于有時希望能夠將BUTTON B列按鈕視為單個復合單元,例如在顯示和隱藏它們時,將它們作為單獨的“容器”嵌套在內部tk.Frame會更容易,因為它們都可以通過僅僅改變它而不是受到影響處理組中的每個小部件。
這就是我的意思:
import tkinter as tk
root = tk.Tk()
root.title("Analyser")
root.geometry("750x250")
grp_number_var = tk.StringVar()
l0 = tk.Label(root, textvariable=grp_number_var, width=20)
l0.grid(row=1, column=1)
def func(n):
grp_number_var.set("Selected Button: Button " str(n))
BUTTON_GROUPS = {
"Group 1": ["Button 1", "Button 2", "Button 3"],
"Group 2": ["Button 1"],
}
# Label headers.
tk.Label(root, text="BUTTONS A", font=('Helvetica', 12, "bold"),
fg='white', bg='#107baf', width=20).grid(
row=0, column=0, padx=4, pady=8)
tk.Label(root, text="BUTTONS B", font=('Helvetica', 12, "bold"),
fg='white', bg='#107baf', width=20).grid(
row=0, column=2, padx=4, pady=8)
group_buttons = []
button_frames = []
def show_frame(group_btn, btn_frame):
"""Make specified group button active and its associatge button frame
visible and hide previously one.
"""
grp_number_var.set('') # Clear label.
for btn in group_buttons:
if btn is group_btn:
btn.config(bg='#42bed8')
else:
btn.config(bg='#d8e7ea')
for frame in button_frames:
if frame is btn_frame:
frame.grid()
elif frame.winfo_ismapped():
frame.grid_remove()
# Create BUTTON A column group buttons and associated BUTTON B column buttons.
for row, grp_name in enumerate(BUTTON_GROUPS, start=1):
# BUTTON A column group button.
btn = tk.Button(root, text=grp_name, font=('Helvetica', 10),
bg='#d8e7ea', width=20)
btn.grid(row=row, column=0, padx=4, pady=8, sticky='n')
group_buttons.append(btn)
btn_frame = tk.Frame(root)
num_btns = len(BUTTON_GROUPS[grp_name]) # Number of buttons in 2nd column.
btn_frame.grid(row=1, column=2, sticky='n', rowspan=num_btns)
btn_frame.grid_remove() # Initially invisible.
button_frames.append(btn_frame)
# Configure column button to toggle button frame's visibility.
btn.config(command=lambda group_btn=btn, btn_frame=btn_frame:
show_frame(group_btn, btn_frame))
# BUTTON B column buttons.
for i, sub_group_btn in enumerate(BUTTON_GROUPS[grp_name], start=1):
btn = tk.Button(btn_frame, text=sub_group_btn, font=('Helvetica', 10),
bg='#d8e7ea', width=20, activebackground='#42bed8')
btn.config(command=lambda n=i: func(n))
btn.grid(row=row i, column=2, padx=4, pady=4)
root.mainloop()
這是一個顯示最初顯示的螢屏截圖,然后是另外兩個顯示單擊相應組按鈕時發生的情況:



uj5u.com熱心網友回復:
使用字典而Buttons_A不是分隔串列更容易關聯所需的串列:
Buttons_A = {
"Button 1": ["Button 1", "Button 2", "Button 3"],
"Button 2": ["Button 1"]
}
還可以更好地使用框架對按鈕進行分組,這樣您就可以銷毀“按鈕 B”中的按鈕,然后在單擊“按鈕 A”中的按鈕時創建新按鈕。
import tkinter as tk
root = tk.Tk()
root.title("Analyser")
root.geometry("750x250")
group_number = tk.StringVar()
l0 = tk.Label(root, textvariable=group_number, width=20)
l0.grid(row=1, column=1, sticky='n')
def func(btn):
group_number.set("Selected Button: " btn)
# clear current buttons shown in frame_B
for w in frame_B.winfo_children():
w.destroy()
# populate required buttons
for item in Buttons_A[btn]:
btn = tk.Button(frame_B, text=item, font=('Helvetica', 10), bg='#d8e7ea', width=20, activebackground='#42bed8')
btn.pack(padx=4, pady=4)
Buttons_A = {
"Button 1": ["Button 1", "Button 2", "Button 3"],
"Button 2": ["Button 1"]
}
l2 = tk.Label(root, text="BUTTONS A", font=('Helvetica', 12, "bold"), fg='white', bg='#107baf', width=20)
l2.grid(row=0, column=0, padx=4, pady=8)
# frame for "Buttons A"
frame_A = tk.Frame(root)
frame_A.grid(row=1, column=0, sticky='n')
for item in Buttons_A:
btn = tk.Button(frame_A, text=item, font=('Helvetica', 10), bg='#d8e7ea', width=20, activebackground='#42bed8')
btn.config(command=lambda x=item:func(x))
btn.pack(padx=4, pady=4)
l2 = tk.Label(root, text="BUTTONS B", font=('Helvetica', 12, "bold"), fg='white', bg='#107baf', width=20)
l2.grid(row=0, column=2, padx=4, pady=8)
# frame for "Buttons B"
frame_B = tk.Frame(root)
frame_B.grid(row=1, column=2, sticky='n')
root.mainloop()
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/482883.html
