I'm creating a GUI in tkinter, and am trying to use list comprehension for the creation of buttons. However, I struggle getting the list comprehension to actually replace 'btn' with the names in 'btn_list'. I'd appreciate if anyone knew of a clever way of doing this.
start_btn, pause_btn, reset_btn, stat_btn = (Button(),) * 4
btn_list = [start_btn, pause_btn, reset_btn, stat_btn]
[btn.grid(row=2, column=col) for col, btn in enumerate(btn_list)]
CodePudding user response:
When you do (Button(),) * 4, you get a tuple containing 4 times the same button. If you want 4 different buttons, you can do it with a list comprehension:
btn_list = [Button() for i in range(4)]
I do not see the point of using a list comprehension instead of a regular for loop to grid them though because it gives you a useless list of None.
CodePudding user response:
If you create the button in a class instead, and add initiate the class for each item in the list comprehension, that should work.
import tkinter as tk
class CreateButton:
"""Create button class"""
def __init__(self, **kwargs):
self.button = tk.Button(**kwargs)
window = tk.Tk()
button_text = ["Test1", "Test2"]
buttons = [CreateButton(master=window, text=text, width=20) for text in button_text]
for button in buttons:
button.button.pack()
window.mainloop()
