Skip to content Skip to sidebar Skip to footer

Python 'str' Object Has No Attribute 'config'

I tried to create a Gui with a grid like label, the label will randomly fill with number in random label with a click on the start button. I cannot get the code to recognize the ra

Solution 1:

If you want a grid of buttons, it would make sense to use a 2d list:

from tkinter import *
import random

# Create variables for these for the grid width/height
width = 3
height = 5

def fill_auto():
    for i in range(1, 6):
        rd_row = random.randrange(0, height)
        rd_col = random.randrange(0, width)
        rd_num = random.randrange(1, 16)
        # Set the label text
        matrix[rd_row][rd_col].config(text = str(rd_num))


root = Tk()
root.geometry('+0+0')
root.configure(bg='black')

# Helper function to create a label
def make_label(x, y):
    l = Label(root, width=5, relief='solid')
    l.grid(column=x, row=y)
    return l;

# Using list comprehension to create 2d list
matrix = [[make_label(x,y) for x in range(width)] for y in range(height)]

btn = Button(root, text='start', command=fill_auto)
btn.grid(row=6, column=1)

root.mainloop()

Post a Comment for "Python 'str' Object Has No Attribute 'config'"