Python Forum
[Tkinter] problem with button events
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] problem with button events
#4
The event handler doesn't have any concept of which i it should be referring to.  It doesn't capture the value when you create it, and instead uses whatever i is when the event handler fires off, which is 9 (unless you click it really fast, before all of them exist).

You can get around that by having a local variable for the event handler which is unique to each event handler.  As was shown above, one way to do that is with a class.  Another is to build a new event handler each time, like so:
# this function is unchanged from your code...
def click(num):
    print(num)

def build_click_handler(num):
    return lambda: click(num)

for i in range(10):
    b = tkinter.Button(root, text = i, command = build_click_handler(i))
Reply


Messages In This Thread
problem with button events - by Lubik_ - Dec-01-2017, 02:35 PM
RE: problem with button events - by Larz60+ - Dec-01-2017, 05:06 PM
RE: problem with button events - by Windspar - Dec-01-2017, 06:38 PM
RE: problem with button events - by nilamo - Dec-01-2017, 06:52 PM
RE: problem with button events - by Windspar - Dec-01-2017, 08:47 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  problem with radio button crook79 3 3,625 Aug-12-2021, 02:30 PM
Last Post: deanhystad
  tkinter python button position problem Nick_tkinter 3 3,482 Jan-31-2021, 05:15 AM
Last Post: deanhystad
  [Tkinter] Button click problem using OOP JohnB 5 3,519 Oct-21-2020, 12:43 PM
Last Post: JohnB
  Problem about image and button scotesse 5 2,879 Apr-27-2020, 10:09 AM
Last Post: scotesse
  Problem with Submit button Tkinter Reldaing 2 3,603 Jan-05-2020, 01:58 AM
Last Post: balenaucigasa
  [PyQt] Wonky Touch Events hessej 2 2,248 Nov-07-2019, 07:52 PM
Last Post: kozaizsvemira
  [PyQt] Problem how to click a button inside a group box? mart79 2 3,375 Aug-05-2019, 01:21 PM
Last Post: mart79
  [PySimpleGui] How to alter mouse click button of a standard submit button? skyerosebud 3 4,947 Jul-21-2019, 06:02 PM
Last Post: FullOfHelp
  [PyQt] touch events is not generating shridhara 0 3,311 Apr-23-2018, 11:39 AM
Last Post: shridhara
  [Tkinter] Problem with changing label text on button press xk2006x 1 5,542 Jun-02-2017, 06:00 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020