profile for Gajendra D Ambi on Stack Exchange, a network of free, community-driven Q&A sites

Wednesday, November 22, 2017

Python 3.6 GUI with tkinter

There is no fun in using an application which does not have a graphical user interface. When you are trying to make a game or a program and if it is for those who are not coders then tkinter is here for the rescue.
Get your notebook here.


import tkinter as tk

# create a window
window = tk.Tk()

# start the GUI
window.mainloop()

tkinter is a built in GUI module. Here we are importing it. Creating a window. We can run just this code but the window will disappear too fast. saying window.mainloop() will make it stay till we close it.
I urge you to always do the following when you are exploring a module.


dir(tkinter)
help(tkinter)

Once you are done exploring the module then let us improvise on our previous work.
  1. create a Label for our window
  2. Give it a label
  3. define a size for the window
import tkinter as tk
from tkinter import ttk # this is needed to add buttons and labels

# create a window
window = tk.Tk()
window.title('Justice League') # let us give a title to our window
window.geometry("500x400") 

# start the GUI
window.mainloop()

What is the use of this justice league window without it's members? The house is empty. Let us bring in our heroes.


import tkinter as tk
from tkinter import * # this is needed to add buttons and labels

# create a window
window = tk.Tk()
window.title('Justice League') # let us give a title to our window
window.geometry("500x400") # 

# Let us add our members to the window
T = tk.Text(window)
T.pack()
T.insert(tk.END, "Batman \nSuperman \nFlash \nAquaman \nWonder woman \nCyborg")

# Start the GUI event loop
window.mainloop()

You can easily make out that we are now adding text to the window. This is how you add text in tkinter so I will not try to pour any logic here. You just have to remember it or do it so many times to that you won't forget.
If you run it now, you will have the text displayed. Why stop there? Let us add a button, give it a name and when you click on it, it will display the true identity of the members of the justice league.


import tkinter as tk
from tkinter import ttk # this is needed to add buttons and labels

# create a window
window = tk.Tk()
window.title('Justice League') # let us give a title to our window
window.geometry("500x400") 

# Let us add our members to the window
T = Text(window, height=10, width=30) # define the area of text
T.pack()
T.insert(END, "Batman \nSuperman \nFlash \nAquaman \nWonder woman \nCyborg")

# member's real identity
def RevealId():
    print("Batman is Bruce Wayne \nSuperman is Clark Kent \nFlash is Barry Allen \
    \nAquaman is Arthur Curry \nWonder woman is Diana Prince \nCyborg is Victor Stone")

# add a button to do some stuff
b = Button(text="Reveal their identity", command=RevealId)
b.pack()

# Start the GUI event loop so that it won't close
window.mainloop()

go on. explore more.