Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...