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,
Solution 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 ---defclaim_field(x, y):
buttons[(x,y)]['state'] = 'disabled'
buttons[(x,y)]['bg'] = 'red'# --- main ---
root = tk.Tk()
buttons = {}
for x inrange(0, 7):
for y inrange(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()
Post a Comment for "Python Tkinter - Dictionary With Buttons - How Do You Disable Them?"