If I were to make a button or label that won't be called or re-configed anywhere else in the code should I make it a variable or just create that instance? Just instantiating it makes it more readable IMO and uses less memory (not that I have to think about it using python), but I see most people creating a instance variable. Which one is the "better" way of writing it (assuming I don't need to call it later)?
Button(root, text="Button").grid(row=0, column=0)
or
self.my_button = Button(root, text="Button")
self.my_button.grid(row=0, column=0)
CodePudding user response:
I always assign widgets to variables. They aren't always instance variables; sometimes they are local variables. I'll use instance or global variables if I ever need to reference the widget outside of the function where it is defined.
In my opinion, tkinter code is much easier to understand when widgets are created and laid out in separate blocks and grouped together logically. When all of the layout code is in a block it's much easier to visualize the layout.
In other words, instead of this:
root = Tk()
Canvas(root, ...).grid(...)
toolbar = Frame(root,...).grid(...)
Label(toolbar,...).pack(...)
Button(toolbar, ...).pack(...)
... I prefer this:
toolbar = Frame(root, ...)
canvas = Canvas(root, ...)
app_icon = Label(toolbar,...)
save_button = Button(toolbar, ...)
toolbar.grid(...)
canvas.grid(...)
app_icon.pack(...)
save_button.pack(...)
I think it becomes much more clear that the toolbar and canvas are laid out together in the window, and that the label and icon are part of the toolbar.