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

编程入门 行业动态 更新时间:2024-10-24 16:22:18
本文介绍了python'str'对象没有属性'config'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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 random label and set text to it. The labels are create in a loop for the grid of '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()

推荐答案

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

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

更多推荐

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

本文发布于:2023-10-16 16:48:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1498158.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   对象   python   config   str

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!