Change your lambda to lambda i=i: self.open_this(i).

This may look magical, but here's what's happening. When you use that lambda to define your function, the open_this call doesn't get the value of the variable i at the time you define the function. Instead, it makes a closure, which is sort of like a note to itself saying "I should look for what the value of the variable i is at the time that I am called". Of course, the function is called after the loop is over, so at that time i will always be equal to the last value from the loop.

Using the i=i trick causes your function to store the current value of i at the time your lambda is defined, instead of waiting to look up the value of i later.

Answer from BrenBarn on Stack Overflow
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ looping-through-buttons-in-tkinter
Looping through buttons in Tkinter - GeeksforGeeks
July 23, 2025 - For the button command, create a function named 'action' and for each button call the text_update() function to update the changes in the entry in Entry() object created earlier. ... # Import package and it's modules from tkinter import * # ...
Discussions

using for loop to create buttons (tkinter)
lambda: button_click((x, y), current_fleet) doesn't create a closure over x and y because they're not local names, they're global names (defined in top-level scope.) To create a closure, the name has to be defined in a local scope: def lambda_maker(x, y): return lambda: button_click((x, y), current_fleet) for x in range(10): #use this as row count for y in range(10): Button(root, [...], command=lambda_maker(x, y)) More on reddit.com
๐ŸŒ r/learnpython
4
1
January 2, 2021
python - Looping Buttons in tkinter and function assignment - Stack Overflow
Here's a short but complete example of creating buttons in a loop: import tkinter as tk from tkinter import ttk from functools import partial root = tk.Tk() def print_sheet(i): print("printing sheet %d" % i) for i in range(0, 5): button = ttk.Button(root, text="Button %d" % i, command=part... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - Iterating through buttons in tkinter - Stack Overflow
I try to create buttons in tkinter using a loop. def bulkbuttons(): i = 0 x = 0 buttons=[] while x More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - More efficient way to generate Tkinter buttons in loops - Code Review Stack Exchange
I designed a game of Minesweeper where the board was displayed using text, and it worked fine. Using the same pseudocode, I tried to write the game with a GUI using Tkinter, and made a few modifica... More on codereview.stackexchange.com
๐ŸŒ codereview.stackexchange.com
April 1, 2023
๐ŸŒ
Plus2Net
plus2net.com โ€บ python โ€บ tkinter-button-dynamic.php
Dynamic Handling of buttons in Tkinter
February 5, 2019 - So each button ( time ) we will assign the value to another variable to pass it through loop. import tkinter as tk from tkinter import * my_w = tk.Tk() my_w.geometry("200x200") # Size of the window my_w.title("www.plus2net.com") # Adding a title ...
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ article โ€บ how-to-create-tkinter-buttons-in-a-python-for-loop
How to create Tkinter buttons in a Python for loop?
1 month ago - In this example, we will create ... Example") root.geometry("400x300") # Create buttons using for loop for i in range(5): button = ttk.Button(root, text=f"Button {i}") button.pack(pady=5) root.mainloop()...
Top answer
1 of 5
1
Bumsfeld, you saved me! ยท I encountered the following problem in my code that displays the date in boxes for each day of the current week, and allows scheduling events for each day. ยท for i in range(7): ยท date = getDate(i) #This returns the date for each box in the row. ยท button = tk.Button(row) ยท button.configure(text=date)#This works fine for assigning text to the buttons. Each date value is unique for each button. ยท button.configure(command=lambda: createEvent(date)) #This does not work, because the function does not pass unique date values in the argument. Every button passes the same date value. ยท button.pack() ยท The createEvent()creates a new window to enter in event details for a particular date. However, createEvent(date) always passes the last date value for every box. Thus, even though I clicking on Monday's box (3/5/2012), the createEvent() still uses Sunday's date (3/11/2012). Instead of creating new function objects, tkinter always refers back to the original function object and updates it. This is not expected behavior, especially since the "command" attribute is the only tkinter attribute I have found that behaves like this. ยท However, it is solvable by borrowing from bumsfeld. Create the lambda argument outside of the tkinter argument: ยท action = lambda: createEvent(date) #Does not work ยท action = lambda x = date: createEvent(x) #This does work ยท button.configure(command=action) ยท As a follow up, can anyone point me to a resource that explains why Tkinter/Python behaves like this?
2 of 5
0
Read and experiment this part of the tutorial of python.org, I would like to encourage to go through all of the tutorial and experiment with variations of example code.http://docs.python.org/tutorial/controlflow.html
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ using for loop to create buttons (tkinter)
r/learnpython on Reddit: using for loop to create buttons (tkinter)
January 2, 2021 -

I am trying to have a quick way to implement buttons as I need 100 of it but when I implement it using forloop, on any button press the output is only (9, 9)

for x in range(10): #use this as row count
for y in range(10):

Button(root, text="", padx=px, pady=py, command=lambda: button_click((x, y), current_fleet)).grid(column=y, row=x, sticky=W)

๐ŸŒ
Quora
quora.com โ€บ How-could-I-create-a-set-of-buttons-with-a-loop-in-Tkinter
How could I create a set of buttons with a loop in Tkinter? - Quora
Answer: Consider the code photo below : I have created 4 button using loops in Tkinter. Output : NOTE : Few things to note here, 1. These buttons don't do some actions as I have not defined function to them. And that will be slight hard to do if we are using loops. 2. You can use any method t...
Find elsewhere
Top answer
1 of 2
1

Define a function to print the contents of one sheet, taking the sheet number as an argument. Then, use functools.partial to associate a command with each button:

def print_sheet(sheet_number):
    ...

for i in range(0, num_sheets):
    an_sheet = ttk.Button(..., command = partial(print_sheet, i))
    ...

Here's a short but complete example of creating buttons in a loop:

import tkinter as tk
from tkinter import ttk
from functools import partial

root = tk.Tk()

def print_sheet(i):
    print("printing sheet %d" % i)

for i in range(0, 5):
    button = ttk.Button(root, text="Button %d" % i,
                        command=partial(print_sheet, i))
    button.pack()

root.mainloop()
2 of 2
0

So you are asking about how to iterate through a set of functions and assign them?

You could use a dictionary

Example from my A-level computing coursework

self.screen_info = {"Email Customer":  {"button_names": ["Enter Email"],         "commands": [self.email_from_email]},
                    "Text Customer":   {"button_names": ["Enter Number"],        "commands": [self.text_from_number]},
                    "Backup Database": {"button_names": ["Choose Location"],     "commands": [backup_database.backup]},
                    "Export Database": {"button_names": ["As .txt", "As .csv"],  "commands": [lambda: export.main("txt"), lambda: export.main("csv")]}}


def populate(self):
    for key in self.screen_info.keys():

        self.screen_info[key]["parent"] = tk.Frame(self.screens, width = 300, height = 300, bg = "#E6E6FA")
        self.screen_info[key]["parent"].place(relx = 0.5, rely = 0.5, anchor = tk.CENTER)

        for num in range(len(self.screen_info[key]["button_names"])):
            self.screen_info[key]["button_names"][num] = tk.Button(self.screen_info[key]["parent"],
                                                                   width = 20,
                                                                   text = self.screen_info[key]["button_names"][num],
                                                                   font = ("Ariel", 11, "bold"),
                                                                   command = self.screen_info[key]["commands"][num])
            self.screen_info[key]["button_names"][num].place(relx = 0.5, y = 60 + num * 40, anchor = tk.CENTER)

So this will iterate through the dictionary creating everything and assign commands. I used lambda for 'Export Database' as the function requires a parameter and if i didn't use lambda then the function would run as soon as the program was launched

EDIT I overwrite each key-value in the dictionary with the associated widget but if you are not referring to them again you don't even need to set a variable, key to them

๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 63388827 โ€บ iterating-through-buttons-in-tkinter
python - Iterating through buttons in tkinter - Stack Overflow
from functools import partial def bulkbuttons(): # Put all formatting related parameters of the Button constructor in a dictionary # Using ** will pass dict values to formatting = {'width': 12, 'borderwidth': 1, 'relief': 'raised', 'bg': '#134f5c', 'fg': '#FFFFFF'} for i in range(10): buttons[i]=Button(window, text=str(i), **formating, command=partial(justprint,i)) buttons[i].grid(row=i, column=2) Your first while loop can be expressed as this pretty and concise list comprehesion: ... Try using this notation when possible, since they will save you typing time and is far more readable. Your second while loop overwrites the list created in the first one, so there is no need to do the first while loop.
๐ŸŒ
TutorialsPoint
tutorialspoint.com โ€บ article โ€บ how-to-change-text-of-tkinter-button-initilised-in-a-loop
How to change text of Tkinter button initilised in a loop?
This creates three buttons labeled "Button 0", "Button 1", and "Button 2" arranged vertically in the window. To make buttons interactive and change their text when clicked, we need to assign command functions. Lambda functions are perfect for this because they allow us to pass specific parameters to the callback function ? import tkinter as tk def update_button_text(button): current_text = button["text"] button.config(text=current_text + " Clicked") def create_interactive_buttons(): buttons = [] for i in range(3): button = tk.Button(root, text=f"Button {i}") button.config(command=lambda b=button: update_button_text(b)) button.pack(pady=5) buttons.append(button) return buttons root = tk.Tk() root.title("Interactive Buttons") root.geometry("300x200") buttons_list = create_interactive_buttons() root.mainloop()
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 74307383 โ€บ tkinter-creating-buttons-in-a-loop
tkinter creating buttons in a loop - Stack Overflow
from tkinter import * Master = Tk() Master.geometry("1920x1080") Master.configure(bg = "#000000") img1C1C1C = PhotoImage(file = f"#1C1C1C.png") img505050 = PhotoImage(file = f"#505050.png") def Enter(Widget, event): if not event.state: Widget.configure(image = img505050) def Leave(Widget, event): if not event.state: Widget.configure(image = img1C1C1C) for Row in range(5): for Column in range(10): x = 25 + 125 * Column + 25 * Column y = 25 + 100 * Row + 25 * Row Widget = Button(master = Master, bg = "#000000", image = img1C1C1C, bd = 0, borderwidth = 0, activebackground = "#000000", relief = "flat", highlightthickness = 0) Widget.bind("<Enter>", lambda event: Enter(Widget, event)) Widget.bind("<Leave>", lambda event: Leave(Widget, event)) Widget.place(x = x, y = y, width = 125, height = 100) Here I am creating a simple script to create some rows of buttons and columns of buttons.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 67625096 โ€บ using-a-for-loop-to-create-buttons-in-tkinter-and-give-them-each-a-unique-input
python - Using a for loop to create buttons in tkinter and give them each a unique input - Stack Overflow
def create_secondwindow_button(): x = 1 y = 0 mypath = "C:\\Users\\Link\\OneDrive\\Desktop\\python stuff\\screenshot example\\All snapshot images" for I in listdir(mypath): btp = mypath +"\\"+str(I) print(btp) screenshot_snap = Button(sec_window,text = str(I), bg = "chocolate3",activebackground = "white",padx= 80,pady =10,command =lambda: image_replacer(y)) screenshot_snap.grid(column = 4, row = int(x),rowspan = 5,columnspan = 5,padx = 50,pady =10) x += 10 if y < 3: y += 1
๐ŸŒ
Finxter
blog.finxter.com โ€บ 5-best-ways-to-create-tkinter-buttons-in-a-python-for-loop
5 Best Ways to Create Tkinter Buttons in a Python For Loop โ€“ Be on the Right Side of Change
March 6, 2024 - The loop simply iterates and creates buttons in a linear fashion. When a more organized layout is needed, using the grid system to place buttons can be very effective. This method involves specifying row and column coordinates for each button, which allows for a more structured arrangement ...
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 66042830 โ€บ making-lots-of-buttons-in-tkinter-with-a-loop
python - Making lots of buttons in tkinter with a loop? - Stack Overflow
def Create(): button1 = Button(root, text="button 1", command=1) button1.grid(row=7, column=0, pady=5) button2 = Button(root, text="button 2", command=2) button2.grid(row=7, column=1, pady=5) button3 = Button(root, text = "button 3", command=3) button3.grid(row=7, column=2, pady=5) button4 = Button(root, text = "button 4", command=4) button4.grid(row=8, column=0, pady=5) button5 = Button(root, text = "button 5", command=5) button5.grid(row=8, column=1, pady=5) button6 = Button(root, text = "button 6", command=6) button6.grid(row=8, column=2, pady=5) button7 = Button(root, text = "button 7", co
๐ŸŒ
Python
mail.python.org โ€บ pipermail โ€บ tkinter-discuss โ€บ 2006-June โ€บ 000795.html
[Tkinter-discuss] creating widgets generically, with a loop?
June 21, 2006 - For example, here's a > snippet of what I currently use: > > ... > Button(top, text="OO design info", > command=self.launch_file23).grid(sticky="w",row=10,column=5) > ... > > ... > def launch_file23 ( self ): os.spawnl ( os.P_NOWAIT , > "c:\\Program Files\\TextPad 4\\TextPad.exe" , "TextPad.exe" , "d:\\My > > > Documents\\prog_oo_design.txt" ) > ... > > If there was a way I could pass arguments to launch_file23 from the > "command=" parameter, that would solve the problem nicely - I could > store the info in an array, and then just loop to create the buttons. > > Any ideas? > > > Michael Stein
๐ŸŒ
Python Forum
python-forum.io โ€บ thread-14116.html
[PyGame] Create multiple buttons in a loop?
Hi, I'm trying to create a screen which will create buttons with each letter of the alphabet and then, when clicked, show a list of buttons with people with names beginning with that letter (from the database). I got the letters screen to run and sh...
Top answer
1 of 1
2

Yes, it is possible.

The following example creates a window with a reset button; upon clicking reset, a frame is populated with buttons corresponding to a random number of buttons chosen randomly from possible subjects. Each button has a command that calls a display function that redirects the call to the proper topic, which, in turn prints the name of its topic to the console, for simplicity of the example. You could easily create functions/classes corresponding to each topic, to encapsulate more sophisticated behavior.

Adding subjects, is as simple as adding a key-value pair in SUBJECTS

Pressing reset again, removes the current button and replaces them with a new set chosen randomly.

import random
import tkinter as tk
from _tkinter import TclError


SUBJECTS = {'Maths': lambda:print('Maths'), 
            'Physics': lambda:print('Physics'),
            'Chemistry': lambda:print('Chemistry'),
            'Biology': lambda:print('Biology'),
            'Astronomy': lambda:print('Astronomy'),
            'Petrology': lambda:print('Petrology'),}

topics = []


def topic_not_implemented():
    print('this topic does not exist')


def get_topics():
    """randomly creates a list of topics for this example
    """
    global topics
    topics = []
    for _ in range(random.randrange(1, len(SUBJECTS))):
        topics.append(random.choice(list(SUBJECTS.keys())))
    return topics


def reset_topics():
    global topics_frame

    try:
        for widget in topics_frame.winfo_children():
            widget.destroy()
        topics_frame.forget()
        topics_frame.destroy()
    except UnboundLocalError:
        print('error')
    finally:
        topics_frame = tk.Frame(root)
        topics_frame.pack()
    for topic in get_topics():
        tk.Button(topics_frame, text=topic, command=lambda topic=topic: display(topic)).pack()


def display(topic):
    """redirects the call to the proper topic
    """
    SUBJECTS.get(topic, topic_not_implemented)()


root = tk.Tk()
reset = tk.Button(root, text='reset', command=reset_topics)
reset.pack()
topics_frame = tk.Frame(root)
topics_frame.pack()
root.mainloop()