![]() |
[Tkinter] proper way of coding - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: GUI (https://python-forum.io/forum-10.html) +--- Thread: [Tkinter] proper way of coding (/thread-36442.html) |
proper way of coding - ebooczek - Feb-20-2022 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. RE: proper way of coding - Larz60+ - Feb-20-2022 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. RE: proper way of coding - menator01 - Feb-20-2022 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() RE: proper way of coding - deanhystad - Feb-20-2022 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() |