gpt4 book ai didi

events - Tkinter - 多个按钮的相同事件

转载 作者:行者123 更新时间:2023-12-01 14:33:54 25 4
gpt4 key购买 nike

使用 Tkinter,我有很多按钮。我希望每次按下任何按钮时都会触发相同的回调函数。如何找出按下了哪个按钮?

def call(p1):
# Which Button was pressed?
pass

for i in range (50):
B1 = Button(master, text = '...', width = 2)
B1.grid(row = i*20, column = 60)
B1.bind('<Button-1>',call)

B2 = Button(master, text = '...', width = 2)
B2.grid(row = i*20, column = 60)
B2.bind('<Button-1>',call)

最佳答案

使用列表来引用动态创建的按钮和 lambda 来存储对按钮对象索引的引用。您可以确定单击了哪个按钮。在以下示例中,我使用 .cget("text")在按钮对象上演示访问按钮小部件。

import tkinter as tk

root = tk.Tk()
root.minsize(200, 200)

btn_list = [] # List to hold the button objects

def onClick(idx):
print(idx) # Print the index value
print(btn_list[idx].cget("text")) #Print the text for the selected button

for i in range(10):
# Lambda command to hold reference to the index matched with range value
b = tk.Button(root, text = 'Button #%s' % i, command = lambda idx = i: onClick(idx))
b.grid(row = i, column = 0)

btn_list.append(b) # Append the button to a list

root.mainloop()

或者,您可以使用绑定(bind),然后从生成的事件对象访问小部件。
import tkinter as tk

root = tk.Tk()
root.minsize(200, 200)

def onClick(event):
btn = event.widget # event.widget is the widget that called the event
print(btn.cget("text")) #Print the text for the selected button

for i in range(10):
b = tk.Button(root, text = 'Button #%s' % i)
b.grid(row = i, column = 0)
# Bind to left click which generates an event object
b.bind("<Button-1>", onClick)

root.mainloop()

关于events - Tkinter - 多个按钮的相同事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35470943/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com