tkinter更新按钮列表,具体取决于单击另一个按钮列表

发布于 2025-02-01 22:15:02 字数 1801 浏览 1 评论 0 原文

我是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()

从按钮列表中选择按钮1时:

”“在此处输入映像说明”

当按钮2从按钮列表中选择按钮2:

”在此处inter

I am new to tkinter. I have a list of buttons A and when I select one of the buttons I can also update a label (see code). Now I would like to have a second list of buttons B where the number of buttons (and functionality) depends on the click on a button from the list of buttons A (I tried to show this in the picture).

What am I doing wrong here? Can you help me please!

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()

When Button 1 is selected from Button List A:

enter image description here

When Button 2 is selected from Button List A:

enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

惯饮孤独 2025-02-08 22:15:02

您应该将按钮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()以显示另一个帧。

You should keep buttons B on list so you could easily destroy them.

When you click button A then it runs func and inside this function you should destroy buttons from list, clear this list, create new buttons and add them to this list.

Code will be simpler if you will keep buttons B1 and B2 as sublists on one list.


Minimal working code.

I removed fonts and colors to show only important elements.

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()

Eventually you could use Frame to group buttons and then you have to destroy only this Frame and it will destroy also buttons.

But you can also first create Frames with buttons and put buttons in frames and later use grid_forget() to remove one frame and grid() to show another frame.

紫瑟鸿黎 2025-02-08 22:15:02

您的应用程序中的两列按钮 - 按钮中的a 列表和按钮b 列表中的两个列 - 可以将其组织为两个级别的层次结构,并在这样的字典:

BUTTON_GROUPS = {
    "Group 1": ["Button 1", "Button 2", "Button 3"],
    "Group 2": ["Button 1"],
}

以上格式的数据可用于推动GUI其余部分的构建。由于需要有时能够将按钮b 列按钮作为单个复合单元,例如显示和隐藏它们时,将它们作为单独的“容器” tk.frame < /code>将变得更容易,因为它们都可以通过仅更改 it 而不是与组个体中的每个小部件进行处理。

我的意思是:

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()

这是一个屏幕截图,显示了最初显示的内容,然后再显示两个单击相应组按钮时发生的情况:

”

​//i.sstatic.net/suaee.png“ rel =“ nofollow noreferrer”>

The two columns of buttons in your application — those in the BUTTON A list and those in the BUTTON B list — can be organized into a two level hierarchy and easily be represented in a dictionary like this:

BUTTON_GROUPS = {
    "Group 1": ["Button 1", "Button 2", "Button 3"],
    "Group 2": ["Button 1"],
}

Data in the above format can be used to drive the construction of the rest of the GUI. Since it's desirable to sometimes be able treat the BUTTON B column buttons as a single compound unit, such as when showing and hiding them, nesting them inside as a separate "container" tk.Frame will make that easier because they can all be affected by merely changing it instead of dealing with each widget in the group individual.

Here's what I mean:

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()

Here's a screenshot showing what's initially displayed, followed by two more showing what happens when corresponding group button is clicked:

screenshot nothing selected

screenshot group button 1 selected

screenshot group button 2 selected

南城旧梦 2025-02-08 22:15:02

使用 dictionary buttons_a 而不是分离列表,更容易将所需列表关联到所需的列表:

Buttons_A = {
    "Button 1": ["Button 1", "Button 2", "Button 3"],
    "Button 2": ["Button 1"]
}

也可以更好地将框架使用到组按钮,以便您可以在“按钮b中” butso “然后在单击“按钮”中的按钮时创建新的。

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()

It is easier to associate the required lists using dictionary for Buttons_A instead of separated lists:

Buttons_A = {
    "Button 1": ["Button 1", "Button 2", "Button 3"],
    "Button 2": ["Button 1"]
}

Also better use frames to group buttons, so that you can just destroy buttons in "BUTTONS B" and then create new ones whenever a button in "BUTTONS A" is clicked.

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()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文