Python 'str'对象没有属性'config'



我尝试创建一个带有网格状标签的 Gui,单击开始按钮,标签将随机填充随机标签中的数字。我无法获得代码来识别随机标签并为其设置文本。标签是在循环中创建的,用于"3 X 5"的网格。

from tkinter import *
import random

lbl1 = {}
lbl2 = {}
lbl3 = {}

def fill_auto():
for i in range(1, 6):
rd_row = random.randrange(1, 6)
rd_col = random.randrange(1, 4)
rd_num = random.randrange(1, 16)
print(rd_row, rd_col, rd_num)
pos = str(rd_col) + str(rd_row)
box = 'lbl' + str(pos)
print(box)
box.config(text=rd_num)

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

for y in range(1, 6):
lbl1[str(y)] = Label(root, width=5, relief='solid')
lbl1[str(y)].grid(row=y, column=0)
lbl2[str(y)] = Label(root, width=5, relief='solid')
lbl2[str(y)].grid(row=y, column=1)
lbl3[str(y)] = Label(root, width=5, relief='solid')
lbl3[str(y)].grid(row=y, column=2)
btn = Button(root, text='start', command=fill_auto)
btn.grid(row=6, column=1)
root.mainloop()

如果你想要一个按钮网格,使用一个 2d 列表是有意义的:

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()

最新更新