Luca Janss
Luca Janss

Reputation: 81

AttributeError: 'str' object has no attribute 'configure'

I'm pretty new to python and Tkinter. I want to create 6 buttons and when you click on one of the buttons, the button text changes. I'm getting this error: AttributeError: 'str' object has no attribute 'configure'.

from tkinter import *

root = Tk()
root.resizable(width=False, height=False)

b1 = Button(root, text = '', width = 10, height = 5, command = lambda: main(1))
b1.grid(row = 0, column = 1)
b2 = Button(root, text = '', width = 10, height = 5, command = lambda: main(2))
b2.grid(row = 0, column = 2)
b3 = Button(root, text = '', width = 10, height = 5, command = lambda: main(3))
b3.grid(row = 0, column = 3)
b4 = Button(root, text = '', width = 10, height = 5, command = lambda: main(4))
b4.grid(row = 1, column = 1)
b5 = Button(root, text = '', width = 10, height = 5, command = lambda: main(5))
b5.grid(row = 1, column = 2)
b6 = Button(root, text = '', width = 10, height = 5, command = lambda: main(6))
b6.grid(row = 1, column = 3)

def main(num):
    something = 'b' + str(num)
    something.configure(text = 'hi')

I did this before so maybe there is a small mistake I made. Thx in advance!

Upvotes: 3

Views: 2681

Answers (1)

Henry James
Henry James

Reputation: 145

Looks like you are trying to create a vairable name by making a string.

So your variable 'something' ends up being "b2" for example which isn't the variable b2.

There's a couple of ways you could do this, one would be put your variables into a dict.

buttons = {'b2': Button(root, text='', width=10, height=5, command=lambda: main(1))}
# or like this once buttons is declared as a dict
buttons['b2'] = Button(root, text='', width=10, height=5, command=lambda: main(1))

Then to access the buttons you would do

buttons['b2'].grid(row = 0, column = 1)
buttons['b2'].configure(text = 'hi')

A faster way as suggested by TheLizzard (I've not tested it)

buttons = []
buttons.append(Button(root, text='', width=10, height=5, command=lambda: main(1)))

Then access by

buttons[0].grid(row=0, column=1)

I guess it is faster but maybe if you're dealing with lots of buttons having a readable key value could win out over performance?

Upvotes: 2

Related Questions