So I'm trying to create a grid of 9 buttons that, when pressed, will display their number. 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?
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.
Turns out the suggestion that acw1668 worked. Simply appending a new string variable worked fine
buttons[i].append(StringVar())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.