如何确定哪个按钮被按下了 Python TKinter 中的按钮网格? [英] How to determine which button is pressed out of Button grid in Python TKinter?

查看:30
本文介绍了如何确定哪个按钮被按下了 Python TKinter 中的按钮网格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Python TKinter 编写一个 GUI,其中我有一个由 24 个按钮组成的网格,这些按钮是我使用循环(不是单独创建的)创建的.有什么方法可以获取我按下的按钮的文本.

I am writing a GUI with Python TKinter where I have a grid of some 24 buttons which I have created using a loop (not individually). Is there any way in which I can get the Text of the button that I pressed.

由于它处于循环中,即使使用 lambda 的回调函数也无济于事.我不想为按下每个不同按钮时发生的情况编写单独的代码.我只需要知道相应按钮的文本,以便我可以启动另一个仅适用于该文本的通用函数.

Since it is in loop, a callback function even with lambda is not helping me. I don't wish to write separate code for, what happens when each different button is pressed. I just need to know the text of the corresponding button so that I could initiate another generic function which works with that text only.

ps:我可以使用 List 和 curselection() 完成相同的任务,但我不希望这样.

ps: I am able to do the same task but with List and curselection() and don't want it this way.

self.num = 11

for r in range(0,5):

   for c in range(0,3):

       R = r; C = c

       resNum = "Ch0"+str(self.num);

       self.button1_rex = tk.Button(self.frame, text = resNum,font=("Helvetica", 14), justify = CENTER,width = 20, command = self.new_window)

       self.button1_rex.grid(row=R, column=C, sticky=W)

       self.num = self.num+1

self.new_window 是打开新窗口的函数,需要根据按钮编号做其他功能(如Ch011"等)

self.new_window is the function that opens a new window and needs to do other functionalities based on the button number (like "Ch011" etc)

推荐答案

最简单的方法就是,在构造按钮时,将名称绑定到命令,或者使用 functools.partiallambda.

The simplest way is just to, when you are constructing the button, bind the name to the command, either using functools.partial or a lambda.

使用functools.partial:

self.button1_rex = tk.Button(..., command=functools.partial(self.new_window, resNum))

使用 lambda:

self.button1_rex = tk.Button(..., command=lambda r=resNum: self.new_window(r))

有关 lambda 的更多信息,请参阅什么是 lambda(函数)?Python tkinter 创建按钮...参数.

For more infomation about the lambda, see What is a lambda (function)? and Python tkinter creating buttons ... arguments.

这篇关于如何确定哪个按钮被按下了 Python TKinter 中的按钮网格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆