Search code examples
pythontkinterclonetk-toolkit

Cloning tkinter Buttons with other function


right now I am working on a python phone book with following layout:

|Name | Surname |

Now I want to create a button for each contacts Name and Surname, so 2 buttons for 1 contact * n. If I press on the Name or Surname a box with more details of the contact should open. Can anyone please help me?

I tried following so far:

prename = ["John", "Jack"]
surname = ["Tompson", "Daniels"]
x = 0
y = 0
for pn in prename:
    pre = Button(main, text=pn)
    pre.grid(row=x, column=0)
    x += 1
for sn in surname:
    sur = Button(main, text=sn)
    sur.grid(row=y, column=1)
    y += 1

Solution

  • You need to associate the buttons with the functions you want to be executed when you press them. I use lambda to pass the specific name to the function call.

    Also; its more readable to use enumerate when you want a loop index.

    from tkinter import *
    
    main = Tk()
    
    prename = ["John", "Jack"]
    surname = ["Tompson", "Daniels"]
    
    def get_prename(n): # Callback function for prename buttons
        print(n)
    
    def get_surname(n): # Callback function for surname buttons
        print(n)
    
    for x, pn in enumerate(prename):
        pre = Button(main, text=pn, command=lambda pn=pn: get_prename(pn))
        pre.grid(row=x, column=0)
    
    for y, sn in enumerate(surname):
        sur = Button(main, text=sn, command=lambda sn=sn: get_surname(sn))
        sur.grid(row=y, column=1)