问题
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 randomx,y
and I can disablebuttons[(x,y)]
I use
lambda
to assing to button function with argumentsx,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