Python Forum
[Tkinter] proper way of coding
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] proper way of coding
#1
I have a question of good practice of using tkinter.
Should the main window be created in a function of outside? Making it as a local doesn't seem to be a good idea, but i lack experience, so I'd like to know the proper way of using it.
Reply
#2
that is a loaded question.
I'd suggest that you go through a good tutorial.

One I like: Modern Tkinter for Busy Python Developers: Quickly learn to create great looking user interfaces for Windows, Mac and Linux using Python's standard GUI toolkit, not free but almost.
ebooczek likes this post
Reply
#3
Quote:Should the main window be created in a function of outside?
I don't understand this question.

The way I usually do the coding in tkinter is make a class.
Example:

import tkinter as tk

class MainWindow:
    def __init__(self, parent):
        self.label = tk.Label(parent, text='Some text in a label')
        self.label.pack()

        button = tk.Button(parent, text='Press Me', command=self.change)
        button.pack()

    def change(self):
        self.label['text'] = 'Label text changed'
        self.label['bg'] = 'lightblue'
        self.label['fg'] = 'red'

def main():
    root = tk.Tk()
    MainWindow(root)
    root.mainloop()

if __name__ == '__main__':
    main()
ebooczek and BashBedlam like this post
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#4
I'm starting to like making an App class for the root window.
import tkinter as tk

class MainWindow(tk.Tk):
    """Root window class"""
    def __init__(self, *args, title="Example", **kwargs):
        super().__init__(*args, **kwargs)
        if title:
            self.title(title)
        self.label = tk.IntVar(value=0)
        tk.Label(self, textvariable=self.label).pack()
        tk.Button(self, text='Press Me', command=self.change, width=30).pack(padx=5, pady=5)
 
    def change(self):
        self.label.set(self.label.get() + 1)

def main():
    app = MainWindow()
    app.mainloop()

if __name__ == '__main__':
    main()
Or skip making a main().
if __name__ == '__main__':
    MainWindow().mainloop()
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Unable pass the proper row number to Menubutton command kenwatts275 2 1,736 Jul-19-2020, 11:46 AM
Last Post: kenwatts275

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020