【问题标题】:Python Tkinter - Dictionary with Buttons - how do you disable them?Python Tkinter - 带有按钮的字典 - 你如何禁用它们?
【发布时间】: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


【解决方案1】:

我现在使用button[(x,y)] = tk.Button() 来保留按钮

  • 我使用random.randrange()生成随机的x,y,我可以禁用buttons[(x,y)]

  • 我使用lambda 与参数x,y 关联到按钮功能,因此功能知道单击了哪个按钮并可以禁用它。

当您禁用随机按钮时,您必须检查它是否处于活动状态。如果它已经被禁用,那么您将不得不选择另一个随机按钮 - 所以您必须使用 while 循环。

import tkinter as tk
import random

# --- functions ---

def claim_field(x, y):
    buttons[(x,y)]['state'] = 'disabled'
    buttons[(x,y)]['bg'] = 'red'

# --- main ---

root = tk.Tk()

buttons = {}

for x in range(0, 7):
    for y in range(0, 7):
        btn = tk.Button(root, command=lambda a=x, b=y:claim_field(a,b))
        btn.grid(row=x, column=y)
        buttons[(x,y)] = btn

# disable random button        
x = random.randrange(0, 7)
y = random.randrange(0, 7)
claim_field(x, y)

root.mainloop()        

【讨论】:

    猜你喜欢
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-22
    • 2017-11-17
    • 2012-04-10
    • 2020-12-19
    • 2013-04-19
    相关资源
    最近更新 更多