简体   繁体   English

Python tkinter 唯一按钮文本变量

[英]Python tkinter unique button text variables

So I'm trying to create a grid of 9 buttons that, when pressed, will display their number.所以我试图创建一个由 9 个按钮组成的网格,当按下这些按钮时,将显示它们的编号。 However I'm having issues, when I press a single button, I end up setting all of their text variables to the same number.但是我遇到了问题,当我按下一个按钮时,我最终将所有文本变量设置为相同的数字。 How can I create a unique textvariable for each button?如何为每个按钮创建唯一的textvariable

Code:代码:

from tkinter import *

root = Tk()

# Initialise items
num = 0
buttons = []
buttons_string = StringVar()


# My button function
def buttons_selection(a):
    print(a)
    buttons[a][1].set(a)


# Buttons is a 2d list where I store the button and it's text variable in
for i in range(9):
    buttons.append([])
    buttons[i].append(0)
    buttons[i].append(buttons_string)

# These for loops create the buttons
for x in range(3):
    for y in range(3):

        buttons[num][0] = Button(root, command=lambda a=num: buttons_selection(a),
                                 textvariable=buttons[num][1],  height=2, width=5) .grid(row=y, column=x)
        num += 1

root.mainloop()

To help clarify a bit more, this particular line is the issue:为了帮助澄清一点,这一行是问题所在:

buttons[num][0] = Button(root, command=lambda a=num: buttons_selection(a),
                                 textvariable=buttons[num][1],  height=2, width=5) .grid(row=y, column=x)

I want to make it so that the textvariable=buttons[num][1] unique variable is stored in the button or something.我想让textvariable=buttons[num][1]唯一变量存储在按钮或其他东西中。

Turns out the suggestion that acw1668 worked.结果表明 acw1668 有效。 Simply appending a new string variable worked fine简单地附加一个新的字符串变量工作正常

buttons[i].append(StringVar())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM