A
A
ajlhimik2018-03-30 16:45:23
Python
ajlhimik, 2018-03-30 16:45:23

How to save a button press (from an array of buttons) to tkinter, why is only the last one saved?

import calendar
import datetime
from functools import partial

def changeBut (event, but, i):
    but["bg"] = "green"
    p.append(i)
    print(i)
    print(p)
def left_click(event, i):
    print(but.text[i])
p = []
m = datetime.date.today()
dof = ['Vs DSdsada','DDDa aaAAAA']
a = calendar.monthrange(m.year, m.month)
root = Tk()
i = 0
s = a[1]+1
de = []
while i < s:
    if i == 0:
        Label(root, text = '').grid(row = 1, column = i+1)
        i+=1
        continue
    Label(root, text = str(i)).grid(row = 1, column = i+1)
    i+=1
i = 0
myrow = 0
while i<s:
    if i == 0:
        Label(root, text=dof[0]).grid(row = 2, column = i+1)
        i+=1
        continue
    but = Button(root, text=i, textvariable=i)
    but.bind("<Button-1>", lambda event, but=but: changeBut(event, but, i))
    #but.bind('<Button-1>', left_click(event, i))
    but.grid(row = 2, column = i+1)
    i+=1
root.mainloop()

in the 'p' array, you need to save the 'textvariable' of the pressed button
for me so far like this:5abe3f4f8ad92090700525.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Ruslan., 2018-03-30
@LaRN

Since the variable i is not a lambda parameter, after the end of the loop, all lambdas will have one last value i = 32
Try this:
but.bind("", lambda event, but=but, i = i: changeBut(event, but, i ))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question