Python Tkinter-带按钮的字典-如何禁用它们? [英] Python Tkinter - Dictionary with Buttons - how do you disable them?

查看:223
本文介绍了Python Tkinter-带按钮的字典-如何禁用它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用字典创建了一个7x7的按钮字段.

I created a 7x7 field of buttons with a dictionary.

问题1:我需要随机禁用用户输入的按钮数量. 用户写一个数字x并且x按钮将被阻止,但是我的程序不得不随机选择它们...
问题2::其余按钮可用.但是,如果单击一个,它们将更改颜色并显示state = tk.DISABLED.

Problem 1: I need to disable a User-Input amount of buttons randomly. The user writes a number x and x buttons will be blocked, but my program has to choose them randomly...
Problem 2: The Rest of the buttons are usable. But if you click one, they will change the color and get state = tk.DISABLED.

如何用充满按钮的字典来完成所有这些工作?

How do I do all that with a dictionary full of buttons?

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

谢谢您的回答,对不起我的英语不好:)

Thank you for your answers, sorry for my bad english :)

推荐答案

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

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

  • I use random.randrange() to generate random x,y and I can disable buttons[(x,y)]

我使用lambda将带参数x,y的按钮功能赋给按钮,以便函数知道单击了哪个按钮,并且可以将其禁用.

I use lambda to assing to button function with arguments x,y so function knows which button was clicked and it can disable it.

当您将禁用随机按钮时,则必须检查其是否处于活动状态.如果已将其禁用,则必须选择另一个随机按钮-因此必须使用while循环.

When you will disable random buttons then you have to check if it active. If it is already disabled then you will have to select another random button - so you will have to use while loop.

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

这篇关于Python Tkinter-带按钮的字典-如何禁用它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆