【发布时间】:2018-05-29 00:52:45
【问题描述】:
我用字典创建了一个 7x7 的按钮字段。
问题 1: 我需要随机禁用用户输入数量的按钮。
用户写一个数字 x 和 x 按钮将被阻止,但我的程序必须随机选择它们......
问题 2: 其余按钮均可用。但是如果你点击一个,他们会改变颜色并得到state = tk.DISABLED。
我如何使用一个充满按钮的字典来完成所有这些操作?
buttons = {}
for x in range(0, 7):
for y in range(0, 7):
buttons[tk.Button(frame_2, height=5, width=10, bg="yellow",command=self.claim_field)] = (x, y)
for b in buttons:
x, y = buttons[b]
b.grid(row=x, column=y)
def claim_field():
#changing Color of button and blocking the same button
谢谢你的回答,对不起我的英语不好:)
【问题讨论】:
-
请提供完整的MCVE,以便更轻松地提供帮助。作为一个起点:我将使用列表而不是字典,存储键、值和对按钮的引用的元组。随机选择列表中的一些元素并使用引用选择按钮并更改其属性以禁用按钮或激活颜色更改。
-
command=lambda a=x, b=y:self.claim_field(a,b)和def claim_field(a, b): -
你为什么使用
for b in buttons:?创建按钮时不能直接做吗?b = tk.Button() ; b.grid(x, y) ; button[b] = (x,y)? -
顺便说一句:我宁愿将其保留为
buttons[(x,y)] = tk.Button()并在claim_field(x,y)中使用x,y- 这样claim_field将知道x,y,它可以禁用button[(x,y)]。您可以使用random.randint选择随机x,y来禁用随机按钮。
标签: python dictionary button random tkinter