Tkinter GUI
Tkinter GUI
We saw how you could easily create the main window in just three easy
steps in the previous tutorial. Obviously, the main window alone is of no
use; if we want to create a useful GUI application, we need to add different
buttons & widgets. This is what I will be teaching in this tutorial. So without
any further ado, let's jump to the concepts:
In Python, almost every widget object has several attributes. Here, we’ll talk
about standard widget attributes, including cursors, reliefs, colors, and
fonts.
1. Tkinter Widget state: The state of the widget is defined by state
attributes. NORMAL, ACTIVE, and DISABLED are the values of the
attributes.
2. Tkinter Widget padding: padx and pady –these two attributes come under
the category of widget padding, and they are responsible for adding extra
horizontal and vertical space to the widget. The padx and pady attributes
add space between the buttons.
3. Tkinter Background colors: The background colors of widgets can be set
with the background attributes. It can be abbreviated to bg.
4. Width &Height: The width and height attributes set the width and height
of the widget.
5. Tkinter Fonts: For working with fonts, it has a font module. It has some
built-in fonts such as TkTooltipFont, TkDefaultFont.
6. Tkinter Cursors: The cursor in Tkinter is set with the cursor
7. Tkinter Reliefs: A relief is a border decoration. The possible values
are SUNKEN, RAISED, GROOVE, RIDGE, and FLAT.
Importing tkinter is the same as importing any other module in the Python
code. Note that the module's name in Python 2.x is ‘Tkinter’, and in Python
3.x, it is ‘tkinter’.
from tkinter import *
Copy
To create the main window, Tkinter offers a method, ‘Tk.’ To change the
window's name, you can change the className to the desired one.
imaginary_tech_root = Tk()
Copy
To set the dimensions of the Tkinter window and to set the position of the
main window on the user’s desktop, the geometry() function is used. As in
the example: the width is 644 pixels, and the height is 434 pixels, so that we
can write the function as geometry(644x434).
imaginary_tech_root.geometry("644x434")
Copy
To set the minimum size of the Tkinter window, we use minsize() function,
and to set the maximum size of the Tkinter window, we use maxsize() As in
the example: minsize(300,100) depicts the minimum width and height of
the Tkinter window must be 300 pixels and 100 pixels respectively. In the
same way, maxsize(1200,988) depicts the maximum width, and the height
of the Tkinter window must be 1200 and 988, respectively. Note: We have
to put a comma between width and height, unlike the geometry()
function.
imaginary_tech_root.minsize(300,100)
imaginary_tech_root.maxsize(1200, 988)
Copy
To call the Label widget, which is a child of the root widget. The keyword
parameter "text" specifies the text “Shakaib is a good boy, and this is his
GUI” to be shown:
shakaib = Label(text="Shakaib is a good boy and this is his
GUI")
Copy
The pack method tells Tk to fit the size of the window to the given text.
shakaib.pack()
Copy
There is a method known by the name mainloop(), which is used when your
application is ready to run. This is an infinite loop used to run the
application, wait for an event to occur, and process the event as long as the
window is not closed.
imaginary_tech_root.mainloop()
Copy
To create the main window, Tkinter offers a method, 'Tk'. To change the name of the
window, you can change the className to the desired one.
root = Tk()
Copy
To set the dimensions of the Tkinter window and to set the position of the main
window on the user's desktop, the geometry() function is used. As in the example:
the width is 655 pixels, and the height is 333 pixels, so we can write the function
as geometry(655x333).
root.geometry("655x333")
Copy
Copy
In the same way, another Frame f2 is taken, and the attributes are set to the Frame.
Copy
To call the Label widget, which is a child of the root widget. The keyword parameter
"text" specifies the text "Project Tkinter - Pycharm" to be shown, and the pack
method tells Tk to fit the size of the window to the given text where pady adds extra
space (i.e., 142 in this example) from the upper and lower portion of the Frame
widget.
Copy
In the same way, another label is taken, and the attributes are set to the Label.
Copy
There is a method known by the name mainloop(), which is used when your
application is ready to run. This is an infinite loop used to run the application, wait
for an event to occur, and process the event as long as the window is not closed.
root.mainloop()
bg: The normal background color displayed behind the label and indicator.
relief: The type of the border of the frame. Its default value is set to
FLAT. We can set it to any other styles,
i.e., FLAT, RAISED, SUNKEN, GROOVE, RIDGE.
bd: The size of the border in pixels. Default is 2 pixels.
font: Text font to be used for the button’s label.
image: Instead of text, Image to be displayed on the button.
command: Function or method to be called when the button is
clicked. Note: we only have to write the function or method name in
the command attribute. We should not call the function in the
attribute (i.e., If the function is name(), we just have to
write command=name).
Importing tkinter is the same as importing any other module in the Python code.
Note that the name of the module in Python 2.x is ‘Tkinter’, and in Python 3.x, it is
‘tkinter’.
Copy
To create the main window, Tkinter offers a method, ‘Tk’. To change the name of the
window, you can change the className to the desired one.
root =Tk()
Copy
To set the dimensions of the Tkinter window and to set the position of the main
window on the user’s desktop, the geometry() function is used. As in the example:
the width is 655 pixels, and height is 333 pixels, so we can write the function
as geometry(655x333).
root.geometry("655x333")
Copy
To define a function using ‘def’ (i.e., here, two functions, hello() and name() are
defined) and use it in button attributes.
def hello():
print("Hello tkinter Buttons")
def name():
print("Name is harry")
Copy
To take Frame variable as frame and set the attributes- bg (background color) =
“grey”, borderwidth(thickness of the Frame’s border)=6, and relief=SUNKEN. Then
the Frame frame must be packed (here, it is packed on the left side and north-west
corner).
Copy
To take the Button variable (here we take four Button variables b1, b2, b3 & b4) and
use attributes in the Button widget (i.e., for Button b1, the attributes are fg
(foreground color) = “red”, text= “Print now” and command= hello, such that when
the Button name showing as “Print now” is clicked it will call the hello() function
through the command “hello” attribute and it will print “Hello tkinter Buttons”.
Copy
There is a method known by the name mainloop(), which is used when your
application is ready to run. This is an infinite loop used to run the application, wait
for an event, and process the event as long as the window is not closed.
root.mainloop()
Note: If the user enters a string, which is longer than the available
display space of the widget, the content will be scrolled. This means
that the string cannot be seen in its entirety. The arrow keys can be used to
move to the invisible parts of the string. If you want to enter multiple
lines of text, you have to use the text widget. An entry widget is also
limited to a single font.
The Grid() manager is the most flexible of the geometry managers in
Tkinter. The Grid() geometry manager puts the widgets in a 2-dimensional
table. The master widget is split into a number of rows and columns, and
each "cell" in the resulting table can hold a widget.
Note: We can also create layouts using Pack() manager, but it takes a
number of extra frame widgets and a lot of work to make things look good.
If you use the grid manager instead, you only need one call per widget to
get everything laid out properly.
def getvals():
print(f"The value of username is {uservalue.get()}")
print(f"The value of password is {passvalue.get()}")
root = Tk()
root.geometry("655x333")
uservalue = StringVar()
passvalue = StringVar()
userentry.grid(row=0, column=1)
passentry.grid(row=1, column=1)
Button(text="Submit", command=getvals).grid()
root.mainloop()
root = Tk()
def getvals():
print("It works!")
root.geometry("644x344")
#Heading
Label(root, text="Welcome to Sanvee Travels",
font="comicsansms 13 bold", pady=15).grid(row=0, column=3)
root.mainloop()
root = Tk()
def getvals():
print("Submitting form")
print(f"{namevalue.get(), phonevalue.get(),
gendervalue.get(), emergencyvalue.get(),
paymentmodevalue.get(), foodservicevalue.get()} ")
root.geometry("644x344")
#Heading
Label(root, text="Welcome to Harry Travels",
font="comicsansms 13 bold", pady=15).grid(row=0, column=3)
root.mainloop()
<Button-1>: A mouse button is pressed over the widget. Button 1 is the leftmost button,
Button 2 is the middle button (where available), and Button 3 is the rightmost button.
<B1-Motion>: The mouse is moved, with mouse button 1 being held down (use B2 for the
middle button, B3 for the right button).
<Double-Button-1>: Button 1 was double-clicked. You can use Double or Triple as
prefixes. Note: Both bindings will be called if you bind to both a single click (<Button-
1>) and a double click.
<Enter>: The mouse pointer entered the widget. Note: This event doesn’t mean that the
user pressed the Enter key.
Event attributes:
As Event attributes, we can use width, height, char, num, widget, etc.
def harry(event):
print(f"You clicked on the button at {event.x},
{event.y}")
root = Tk()
root.title("Events in Tkinter")
root.geometry("644x334")
widget.bind('<Button-1>', harry)
widget.bind('<Double-1>', quit)
root.mainloop()
Copy
Menus & Submenus In Tkinter Python |
Python Tkinter GUI Tutorial In Hindi #17
The Menu widget is used to implement different types of menus (toplevel, pulldown,
and popup menus). The goal of this widget is to allow us to create all kinds of menus
that can be used by our applications. It is also possible to use other extended
widgets to implement new types of menus, such as the OptionMenu widget, which
implements a special type that generates a pop-up list of items within a selection.
Attributes:
bg: The background color for choices not under the mouse.
bd: The width of the border around all the choices. Default is 1.
fg: The foreground color used for choices not under the mouse.
tearoff: Normally, a menu can be torn off. The first position (position 0) in the list of choices
is occupied by the tear-off element and the additional choices are added starting at position
1. If you set tearoff=0, the menu will not have a tear-off feature and choices will be added
starting at position 0.
relief: The default 3-D effect for menus is relief=RAISED.
title: Normally, the title of a tear-off menu window will be the same as the text of the
menubutton or cascade that lead to this menu. If you want to change the title of that
window, set the title option to that string.
def myfunc():
print("Mai ek bahut hi natkhat aur shaitaan function
hoon")
mainmenu = Menu(root)
m1 = Menu(mainmenu, tearoff=0)
m1.add_command(label="New project", command=myfunc)
m1.add_command(label="Save", command=myfunc)
m1.add_separator()
m1.add_command(label="Save As", command=myfunc)
m1.add_command(label="Print", command=myfunc)
root.config(menu=mainmenu)
mainmenu.add_cascade(label="File", menu=m1)
m2 = Menu(mainmenu, tearoff=0)
m2.add_command(label="Cut", command=myfunc)
m2.add_command(label="Copy", command=myfunc)
m2.add_separator()
m2.add_command(label="Paste", command=myfunc)
m2.add_command(label="Find", command=myfunc)
root.config(menu=mainmenu)
mainmenu.add_cascade(label="Edit", menu=m2)
root.mainloop()
Copy
Parameters:
Copy
1. default: The default option is used to specify the default button, such as
ABORT, RETRY, or IGNORE, in the message box.
2. parent: The parent option is used to specify the window on top of which
the message box is to be displayed.
def myfunc():
print("Mai ek bahut hi natkhat aur shaitaan function
hoon")
def help():
print("I will help you")
tmsg.showinfo("Help", "Sanvee
will help you with this gui")
def rate():
print("Rate us")
value = tmsg.askquestion("Was your experience Good?",
"You used this gui.. Was your experience
Good?")
if value == "yes":
msg = "Great. Rate us on appstore please"
else:
msg = "Tell us what went wrong. We will call you
soon"
tmsg.showinfo("Experience", msg)
def divya():
ans = tmsg.askretrycancel("Divya se dosti kar lo",
"Sorry divya nahi banegi aapki dost")
if ans:
print("Retry karne pe bhi kuch nahi hoga")
else:
print("Bahut badiya bhai cancel kar diya warna
pitte")
mainmenu = Menu(root)
m1 = Menu(mainmenu, tearoff=0)
m1.add_command(label="New project", command=myfunc)
m1.add_command(label="Save", command=myfunc)
m1.add_separator()
m1.add_command(label="Save As", command=myfunc)
m1.add_command(label="Print", command=myfunc)
root.config(menu=mainmenu)
mainmenu.add_cascade(label="File", menu=m1)
m2 = Menu(mainmenu, tearoff=0)
m2.add_command(label="Cut", command=myfunc)
m2.add_command(label="Copy", command=myfunc)
m2.add_separator()
m2.add_command(label="Paste", command=myfunc)
m2.add_command(label="Find", command=myfunc)
root.config(menu=mainmenu)
mainmenu.add_cascade(label="Edit", menu=m2)
m3 = Menu(mainmenu, tearoff=0)
m3.add_command(label = "Help", command=help)
m3.add_command(label = "Rate us", command=rate)
m3.add_command(label = "Befriend Divya", command=divya)
mainmenu.add_cascade(label="Help", menu=m3)
root.config(menu=mainmenu)
root.mainloop()
Copy
The Listbox() widget is a standard Tkinter widget that displays a list of items from
which a user can select a number of items. The Listbox can only contain text items,
and all items must have the same font and color. Depending on the widget
configuration, the user can choose one or more alternatives from the list.
Listboxes are used to select from a group of textual items. Depending on how the
Listbox is configured, the user can select one or many items from that list.
Attributes:
Methods:
def add():
global i
lbx.insert(ACTIVE, f"{i}")
i+=1
i = 0
root = Tk()
root.geometry("455x233")
root.title("Listbox tutorial")
lbx = Listbox(root)
lbx.pack()
lbx.insert(END, "First item of our listbox")
Set the widget’s yscrollcommand callbacks to the set method of the Scrollbar.
widget(yscrollcommand = scrollbar.set)
Copy
Set the Scrollbar’s command to the yview method of the widget using config().
scrollbar.config(command=widget.yview)
Copy
Attributes:
bg: It is used to set the color of the slider and arrowheads when the mouse is not over them.
bd: The width of the 3-d borders around the trough’s entire perimeter and the width of the
3-d affects the arrowheads and slider. Default is no border around the trough and a 2-pixel
border around the arrowheads and slider.
orient: It is used to set orient=HORIZONTAL for a horizontal scrollbar, orient=VERTICAL for
a vertical one.
width: It sets the width of the Scrollbar (its y dimension if horizontal, and its x dimension if
vertical). Default is 16.
Code is described below:
listbox.pack(fill="both",padx=22)
#text = Text(root, yscrollcommand = scrollbar.set)
#text.pack(fill=BOTH)
scrollbar.config(command=listbox.yview)
#scrollbar.config(command=text.yview)
root.mainloop()
Copy
def newFile():
global file
root.title("Untitled - Notepad")
file = None
TextArea.delete(1.0, END)
def openFile():
global file
file = askopenfilename(defaultextension=".txt",
filetypes=[("All Files", "*.*"),
("Text Documents",
"*.txt")])
if file == "":
file = None
else:
root.title(os.path.basename(file) + " - Notepad")
TextArea.delete(1.0, END)
f = open(file, "r")
TextArea.insert(1.0, f.read())
f.close()
def saveFile():
global file
if file == None:
file = asksaveasfilename(initialfile =
'Untitled.txt', defaultextension=".txt",
filetypes=[("All Files", "*.*"),
("Text Documents",
"*.txt")])
if file =="":
file = None
else:
#Save as a new file
f = open(file, "w")
f.write(TextArea.get(1.0, END))
f.close()
root.title(os.path.basename(file) + " -
Notepad")
print("File Saved")
else:
# Save the file
f = open(file, "w")
f.write(TextArea.get(1.0, END))
f.close()
def quitApp():
root.destroy()
def cut():
TextArea.event_generate(("<>"))
def copy():
TextArea.event_generate(("<>"))
def paste():
TextArea.event_generate(("<>"))
def about():
showinfo("Notepad", "Notepad by Code With Harry")
if __name__ == '__main__':
#Basic tkinter setup
root = Tk()
root.title("Untitled - Notepad")
root.wm_iconbitmap("1.ico")
root.geometry("644x788")
#Add TextArea
TextArea = Text(root, font="lucida 13")
file = None
TextArea.pack(expand=True, fill=BOTH)
root.mainloop()