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

时间:2018-05-22 14:19:10

标签: python-3.6

我尝试使用网格状标签创建一个Gui,标签将随机填充数字随机标签,点击开始按钮。我无法让代码识别随机标签并为其设置文本。标签是为#3; 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()

1 个答案:

答案 0 :(得分:0)

如果你想要一个按钮网格,那么使用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()