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
#2
With a trick, you could use command with partial, to call the callback together with the instance of the button itself as the first argument.

Example:
from tkinter import Tk, Button
from tkinter.messagebox import showinfo
from itertools import product
from functools import partial


class Gui(Tk):
    def __init__(self):
        super().__init__()
        self.setup()
        self.selected: None | Button = None

    def setup(self):
        for number, (col, row) in enumerate(product(range(10), range(5))):
            button = Button(self, text=f"Button {number:02d}")
            # callback, which also submits the button innstance to the function
            button["command"] = partial(self.clicked, button)
            button.grid(row=row, column=col)

    def clicked(self, button: Button):
        print(button["text"])
        if self.selected:
            self.selected, selected = None, self.selected

            grid1 = button.grid_info()
            grid2 = selected.grid_info()
            button.grid_configure(row=grid2["row"], column=grid2["column"])
            selected.grid_configure(row=grid1["row"], column=grid1["column"])
            showinfo(
                "Button position changed",
                f"{selected['text']} swapped with {button['text']}",
            )

        else:
            self.selected = button

if __name__ == "__main__":
    Gui().mainloop()
Clunk_Head likes this post
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
RE: Programmatically creating buttons that remember their positions - by DeaD_EyE - Jun-21-2023, 05:09 PM

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