我一直在开发一个 Python/Tkinter 项目,该项目需要从下面的列表中以编程方式创建按钮。
当按下某个按钮时,我希望该按钮变为“下沉”
,直到按下另一个按钮,在那个阶段该按钮将变为“下沉”
,并且第一次单击的按钮将变为'正常'
。
到目前为止,我不知道如何做到这一点,而无需单独对每个按钮进行编码。
理想情况下,relief
将在 press()
函数中设置。
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()
最佳答案
您正在描述一组单选按钮的行为,因此您应该使用它们。
方便地,单选按钮有一个属性indicatoron
,它
Normally a radiobutton displays its indicator. If you set this option to zero, the indicator disappears, and the entire widget becomes a “push-push” button that looks raised when it is cleared and sunken when it is set. You may want to increase the borderwidth value to make it easier to see the state of such a control.
因此,当设置为零时,它会精确执行您的请求。
关于python - 如何在 tkinter 中以编程方式将相同的操作关联到一组按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31497374/