Conceptual question (and optimization) of creating a bunch of buttons in Tkinter

Viewed 25

I am making a personal project using Tkintr to create an interactive Periodic Table of Elements. Instead of making each Button for each element individually, I used the following code to create a bunch of buttons (beginner coder so sorry for formatting, etc):

from tkinter import *
from tkinter import messagebox
import pandas as pd

raw_csv = pd.read_csv('data/elements.csv')
el_symbols = {row.Number: row.Symbol for (index, row) in raw_csv.iterrows()}
img_ref_dict = {f'{sym}_img': f'images/{num}.png' for num, sym in el_symbols.items()}


window = Tk()
window.title("Periodic Table of Elements")
window.config(width=1202, height=676)


# All da buttons
# Creating population for button assignment

for name, path in img_ref_dict.items():
    exec(f'{name} = PhotoImage(file="{path}")')
    exec(f'{name}_button = Button(image={name}, highlightthickness=0, command=lambda: popup())')

window.mainloop()

To my understanding, the code contained within .mainloop() is continuously looping so is my for loop creating the buttons repeatedly? Would it be better to just create each button one by one? This method is just so much cleaner to me.

1 Answers

As per @acw1668's advice, you're on the right track but are better off doing something like:

for path in img_ref_dict.values():  # you don't really need 'name'
    img = PhotoImage(file=path)
    btn = Button(image=img, highlightthickness=0, command=lambda: popup())
    btn.pack()  # add the button to the UI (you'll probably want to tweak this a bit)

Minor Edit to say that unless you really need the name for each button image, you could tweak img_ref_dict to create a list of image paths instead, like so:

img_refs = [f'images/{num}.png' for num in el_symbols.keys()]

...and then modify the for loop slightly:

for path in img_refs:
   # yadda yadda
Related