Python Tkinter - Dictionary with Buttons - how do you disable them?

荒凉一梦 提交于 2020-01-06 06:51:07

问题


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

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


回答1:


I use button[(x,y)] = tk.Button() to keep buttons and now

  • I use random.randrange() to generate random x,y and I can disable buttons[(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.

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


来源:https://stackoverflow.com/questions/47821717/python-tkinter-dictionary-with-buttons-how-do-you-disable-them

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!