如何在Tkinter中以编程方式将同一操作与一组按钮相关联?

编程入门 行业动态 更新时间:2024-10-24 18:25:40
本文介绍了如何在Tkinter中以编程方式将同一操作与一组按钮相关联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我一直在研究一个Python/Tkinter项目,该项目要求从列表中以编程方式创建按钮,如下所示.

I have been working on a Python/Tkinter project that requires programatically created buttons from a list as below.

当某个按钮被按下时,我希望该按钮成为"sunken",直到另一个按钮被按下为止,在那个阶段该按钮将成为"sunken",而第一次单击的按钮将成为'normal'.

When a certain button is pressed, I would like that button to become "sunken" until another button is pressed, at that stage that button would become "sunken", and the button first clicked would become 'normal'.

到目前为止,我还没有弄清楚如何做到这一点,而不必单独对每个按钮进行编码.

So far I can't figure out how to do this without having to code each button individually.

理想情况下,将在press()函数中设置relief.

Ideally the relief would be set in the press() function.

import tkinter window = tkinter.Tk() window.title("Practice UI") window.grid() numbers = ["1","2","3","4","5","6","7","8","9"] def buttonCreator(labels): n = 0 button = [] for x in range(0,3): for y in range(0,3): if n<=len(labels)-1: button.append(tkinter.Button(window, text = labels[n], command = lambda x = labels[n]:press(x))) button[n].grid(row = x, column = y) n +=1 def press(value): print(value) buttonCreator(numbers) window.mainloop()

推荐答案

您可以简单地返回button并使用它来访问press()中的按钮:

You could simply return button and use it to access your buttons in press():

import tkinter window = tkinter.Tk() window.grid() # changed to integers so we can loop through the # values in press() and use them as indices numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] def buttonCreator(labels): n = 0 button = [] for x in range(0, 3): for y in range(0, 3): if n <= len(labels) - 1: button.append(tkinter.Button(window, text=labels[n], command=lambda x=labels[n]:press(x))) button[n].grid(row=x, column=y) n += 1 return button # added a return statement def press(value): for x in numbers: # index is x-1 because 1 is in button[0], etc button[x-1]['relief'] = 'sunken' if x == value else 'raised' button = buttonCreator(numbers) window.mainloop()

更多推荐

如何在Tkinter中以编程方式将同一操作与一组按钮相关联?

本文发布于:2023-11-28 13:22:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1642580.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:相关联   中以   按钮   操作   方式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!