Python Forum
[Tkinter] Programmatically creating buttons that remember their positions
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] Programmatically creating buttons that remember their positions
#1
I'm looking to create buttons that remember where they are are in a 2D list. This way they can share a single function that takes their 2D list indices as parameters. Ultimately, I want the button to be able to manipulate its own text without having to have a separate reference for each button outside of the list and without having to have a separate function associated with each button.

The buttons display properly with the correct text, but the lambdas reference only the final values of grid_row and grid_column, so all buttons print "3, 3" when pressed.

from tkinter import *
root = Tk()
root.title(" ")
root.geometry("250x250+0+20")

def button_print(row, column):
    print(f"{row + 1}, {column + 1}")

buttons = []
for grid_row in range(3):
    button_row = []
    for grid_column in range(3):
        button = Button(root, text = f"{grid_row + 1} {grid_column + 1}",
                        command = lambda: button_print(grid_row, grid_column), width = 4, height = 3)
        button.grid(row = grid_row, column = grid_column, padx = (10, 10), pady = (10, 10))
        button_row.append(button)
    buttons.append(button_row)
Reply


Messages In This Thread
Programmatically creating buttons that remember their positions - by Clunk_Head - Jun-21-2023, 02:20 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tkinter] How to add conversions and fix button positions. javesike1262 7 2,975 Jan-31-2021, 04:39 PM
Last Post: deanhystad
  Creating a frame with 4 command buttons Heyjoe 5 2,523 Aug-21-2020, 03:16 PM
Last Post: deanhystad
  GUI Tkinter Widget Positions punksnotdead 3 3,021 Jun-12-2019, 06:06 PM
Last Post: Yoriz
  A little idea to remember wxPython classes Sebastian_Adil 0 2,342 Mar-26-2018, 10:23 PM
Last Post: Sebastian_Adil
  Fill out form on webpage and post request programmatically ian 2 3,655 Jul-18-2017, 03:12 PM
Last Post: ian

Forum Jump:

User Panel Messages

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