To create a window in Tkinter using python we need to import Tkinter and declare a root function and a Mainloop function.
This can be done by following the steps below:
- Import Tkinter as tk
- Declare our root function with tk.Tk()
- Initialize our mainloop function with root.mainloop()
import tkinter as tk root = tk.Tk() # Enter your variables and functions here such as buttons and etc root.mainloop() # Anything outside of this mainloop will not be in the window
How do the root function and mainloop work in tkinter?
Whenever we need to create a window in function, we need to first declare the root function and the mainloops, by doing so we let tkinter know that the program needs to be continuously opened in a “while loop” until the operator closes the program. By doing so our tkinter window stays open unless told otherwise.
Since python runs code sequentially, (from top to bottom) we need to declare the stuff we need to appear in our window between our root function and the mainloop. Anything that goes after the mainloop function will not appear in our window.
How do I open the saved Tkinter file in Python?
Depending on the IDE program that you use, some IDEs may not initialize the Tkinter window when you run the code, therefore you want to save your program and run it through a command prompt.
For instance, in my case, I used an anaconda prompt and followed the steps to run my program:
- Locate the saved python file (in my case its in my downloads folder, so cd Downloads)
- Run the saved python file (I saved mine as window, so its python window.py)