[Tutor] accessing buttons (tkinter) made with loop
Peter Otten
__peter__ at web.de
Thu Jun 14 09:51:08 EDT 2018
Freedom Peacemaker wrote:
> Hello Tutor,
> currently im working with tkinter application. Main idea was to create 25
> buttons with for loop. Each button text was random number and user needs
> to click them in order form lowest to highest. When button is clicked its
> being disabled with coresponding color (green-ok, red-not). This is my
> code:
>
> http://pastebin.pl/view/1ac9ad13
That's small enough to incorporate into your message:
> from tkinter import *
> import random
>
> def use():
> if buttons[guzik] == min(buttons.values()):
> guzik.config(state = 'disabled', bg='green')
> #buttons.pop(guzik) # error
> else:
> guzik.config(state = 'disabled', bg='red')
If you make that the buttons' command 'guzik' will always refer to the last
button because that's what the global guzik variable is bound to when the
for loop below ends. One way to set guzik to a specific button is called
"closure" (other options are default arguments and callable classes):
def make_use(guzik):
def use():
if buttons[guzik] == min(buttons.values()):
guzik.config(state = 'disabled', bg='green')
else:
guzik.config(state = 'disabled', bg='red')
del buttons[guzik]
return use
Now the local 'guzik' variable inside make_use() is not changed when the
make_use function ends, and for every call of make_use() the inner use()
function sees the specific value from the enclosing scope.
> num = [x for x in range(1000)]
> buttons = {}
>
> root = Tk()
>
> for i in range(25):
> guzik = Button(root,
> text = random.sample(num,1), height = 1, width = 7)
> guzik.grid(row = int(i/5), column = i%5)
> buttons[guzik] = int(guzik.cget('text'))
guzik["command"] = make_use(guzik)
>
> print(buttons)
>
> root.mainloop()
>
>
> I was looking for help in Google but now i cant figure out, how to move
> forward. I am stuck.
>
> Buttons with numbers are created, and all buttons (key) with their numbers
> (value) are added to buttons dictionary. So objects are created with
> coresponding values. And now is my problem. I tried with use() function
> /it gives me only errors painting few buttons to green, one not painted
> and rest is red/ but i have no idea how i could access configuration of
> those buttons. I think im close but still can see. Can You guide me?
>
> Best Regards
> Pi
More information about the Tutor
mailing list