如何在Tkinter中以编程方式将同一操作与一组按钮相关联? [英] How to associate the same operation to a set of buttons programmatically in 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中以编程方式将同一操作与一组按钮相关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!