GUI: Graphical User Interface
Basics of GUI
- Een GUI is event driven, er zit geen vaste volgorde in de events
- De Python code die we tot nu toe schreven was data driven, daar zit wel een vaste volgorde in events
Data driven VS Event Driven
Een data driven applicatie heeft (eventueel) input van gebruikers maar doorloopt een standaard flow
Een event driven applicatie heeft buttons en andere input items en heeft geen vastgelegde flow voor dataverwerking → Een flowchart tekenen voor een GUI is dus niet mogelijk
Tkinter
Tkinter is een library die geïmporteerd moet worden voordat hij gebruikt kan worden.
GUI’s zijn bijna altijd Object georiënteerd, dit betekent dat ze bijna altijd binnen een class werken.
Zie dia voor voorbeeld:
Text en label
Om een tekst te laten zien op de GUI, gebruik je de volgende codes:
tkinter.Label(parent, options )
- Label() = This function creates a label for your window/frame. This is the most basic of the tkinter functions and is used solely to insert a text that cant be interacted with by the user.
- parent = This parameter is used to represent the parent window (in this case that is self.main_window). In other words, this parameter decides which window/frame the label will be in.
- options = There are many available options which can all be used as key-value pairs, different options can be separated by commas. (I have highlighted the ones I think we’ll need for this period).
- anchor = This option is used to control the positioning of the text if the widget has more space than required for the text. The default is anchor=CENTER, which centers the text in the available space.
- text = The text that the label will consist of.
- bg = The color that the background of the label wil be.
- relief = Decides the depth of the label.
- fg = The color that the text of the label will be in.
- underline = This is used to underline a specific letter in the label.
- wraplength = Instead of having only one line as the label text it can be broken into to the number of lines where each line has the number of characters specified to this option.
- height = This option is used to set the vertical dimension of the new frame.
- width = Width of the label in characters (not pixels!). If this option is not set, the label will be sized to fit its contents.
- bd = This option is used to set the size of the border around the indicator. Default bd value is set on 2 pixels.
- font = If you are displaying text in the label (with the text or textvariable option), the font option is used to specify in what font that text in the label will be displayed.
- cursor = It is used to specify what cursor to show when the mouse is moved over the label. The default is to use the standard cursor.
- textvariable = As the name suggests it is associated with a Tkinter variable (usually a StringVar) with the label. If the variable is changed, the label text is updated.
- bitmap = It is used to set the bitmap to the graphical object specified so that, the label can represent the graphics instead of text.
- image = This option is used to display a static image in the label widget.
- padx = This option is used to add extra spaces between left and right of the text within the label.The default value for this option is 1.
- pady = This option is used to add extra spaces between top and bottom of the text within the label. The default value for this option is 1.
- justify = This option is used to define how to align multiple lines of text. Use LEFT, RIGHT, or CENTER as its values. Note that to position the text inside the widget, use the anchor option. Default value for justify is CENTER.
self.label.pack(side = ‘top’ )
- pack() = The Pack geometry manager packs widgets relative to the earlier widget. Tkinter literally packs all the widgets one after the other in a window. We can use options like fill, expand, and side to control this geometry manager.
- side = The side of the frame the widget will appear at.
- expand = Have the widget expand to stretch across the entire frame.
- fill = Have the widget fill the entire frame
self.window.geometry() (the window stands for the name of your tkinter window)
- geometry() = The geometry function lets you control the size of your window the same way that resolution works, for example:
self.window.geometry(920x380)
Parameteriseren van labels
Om labels aan te passen en aan te geven waar op de GUI ze geprint moeten wordt de volgende code gebruikt:
tkinter.Frame(parent, options)
- Frame() = A frame is a rectangular region on the screen (the GUI). A frame can also be used as a foundation class to implement complex widgets. It is used to organize a group of widgets. Within a frame you have two things to insert: a master and options.
- Master = This parameter is used to represent the parent window (in this case that is self.main_window)
- Options = There are many options which are available and they can be used as key-value pairs separated by commas.
- bg =This option used to represent the normal background color displayed behind the label and indicator.
- bd = This option used to represent the size of the border around the indicator and the default value is 2 pixels.
- cursor = By using this option, the mouse cursor will change to that pattern when it is over the frame.
- height = The vertical dimension of the new frame.
- highlightcolor = This option used to represent the color of the focus highlight when the frame has the focus.
- highlightthickness = This option used to represent the color of the focus highlight when the frame does not have focus.
- highlightbackground = This option used to represent the thickness of the focus highlight.
- relief =The type of the border of the frame. It’s default value is set to FLAT.
- width = This option used to represents the width of the frame.
zie dia 12 en 13 voor voorbeeld
Buttons
To create a button within a tkinter frame/window, you use the following code:
tkinter.Button(parent, options)
- Button() = This command is used to create a clickable widget in a frame, it provides a way for users to trigger actions when clicked.
- parent = This parameter is used to represent the parent window
- options = There are many available options which can all be used as key-value pairs, different options can be separated by commas (I have highlighted the ones I think we’ll need for this period).
- activebackground = Background color when the button is under the cursor.
- activeforeground = Foreground color when the button is under the cursor.
- anchor = Specifies the position of the content (text or image) inside the button.
- bd or borderwidth = Width of the border around the outside of the button
- bg or background = Normal background color.
- command = Function or method to be called when the button is clicked.
- cursor = Selects the cursor to be shown when the mouse is over the button.
- text = Text displayed on the button.
- disabledforeground = Foreground color is used when the button is disabled.
- fg or foreground = The color of the text.
- font = Text font to be used for the button’s label.
- height = Height of the button in text lines
- highlightbackground = Color of the focus highlight when the widget does not have focus.
- highlightcolor = The color of the focus highlight when the widget has focus.
- highlightthickness = Thickness of the focus highlight.
- image = Image to be displayed on the button (instead of text).
- justify = tk.LEFT to left-justify each line; tk.CENTER to center them; or tk.RIGHT to right-justify.
- overrelief = The relief style to be used while the mouse is on the button; default relief is tk.RAISED.
- padx, pady = padding left and right of the text. / padding above and below the text.
- width = Width of the button in letters (if displaying text) or pixels (if displaying an image).
- underline = Default is -1, underline=1 would underline the second character of the button’s text.
- width = Width of the button in letters.
- wraplength = If this value is set to a positive number, the text lines will be wrapped to fit within this length.
dialogs
There are different types of tkinter dialogs, I will go over them in the following section.
I can only explain part of filedialog for now
Filedialog
File dialogs help you open, save files or directories. This is the type of dialog you get when you click file,open. This dialog comes out of the module, there’s no need to write all the code manually.
You can to import filedialog seperately to make the code easier to write and follow, you can do so as follows:
from tkinkter import filedialog as (whatever you want to name it)
-
askopenfilename(options)
- askopenfilename = this function opens a file explorer that, once you have selected a file, will give you the file name, which is in most cases its directory. This is also the function that has been used during the lesson.
- Options = There are a few options for this function, I have listed the ones I have found below. These are important and should be used until further notice.
- title = The title of the window that this function opens.
- initialdir = The directory in which the file explorer will start.
- filetypes = the types of files that the explorer will accept. The format is as follows: (“the name of the file type, this can be anything you want” , “the file extension, bijv: * .txt”)
- Options = There are a few options for this function, I have listed the ones I have found below. These are important and should be used until further notice.
- askopenfilename = this function opens a file explorer that, once you have selected a file, will give you the file name, which is in most cases its directory. This is also the function that has been used during the lesson.
-
askopenfile(options)
- askopenfile = This function allows you to open a file without knowing the directory, instead you can just move through the file explorer and select the file you want to open.
- Options = There are a few options for this function, I have listed the ones I have found below. They are mostly the same as the previous function except for one extra option that is not necessary if you dont want to change anything in the file you are opening.
- title = The title of the window that this function opens.
- initialdir = The directory in which the file explorer will start.
- filetypes = the types of files that the explorer will accept. The format for this is the same as the previous function.
- mode = The mode in which the code will open the selected file. The default variable is ‘r’ or ‘read’. This option is not necessary unless you want to change used mode.
- Options = There are a few options for this function, I have listed the ones I have found below. They are mostly the same as the previous function except for one extra option that is not necessary if you dont want to change anything in the file you are opening.
- askopenfile = This function allows you to open a file without knowing the directory, instead you can just move through the file explorer and select the file you want to open.
More information unavailable, will be updated later.
Entry widget
tkinter.Entry(parent, options)
- Entry() = Creates a widget in the window/frame in which the user can enter a single line of text. This can be used to allow someone to enter their username and/or password among other things. An entry widget consists out of a parent and the options.
- parent = This parameter is used to represent the parent window. In other words, this parameter decides which window/frame the label will be in.
- options = There are many available options which can all be used as key-value pairs, different options can be separated by commas.
- bg = The normal background color displayed behind the label and indicator.
- bd = The size of the border around the indicator. Default is 2 pixels.
- font = The font used for the text.
- fg = The color used to render the text.
- justify = If the text contains multiple lines, this option controls how the text is justified: CENTER, LEFT, or RIGHT.
- relief = With the default value, relief=FLAT. You may set this option to any of the other styles like : SUNKEN, RIGID, RAISED, GROOVE
- show = Normally, the characters that the user types appear in the entry. To make a .password. entry that echoes each character as an asterisk, set show=”* ”.
- textvariable = In order to be able to retrieve the current text from your entry widget, you must set this option to an instance of the StringVar class.
You can use an Entry widget to add a label to your window. This is something you can do with the combination of most of what is in this wiki so far, an example code of this is:
import tkinter
class GUI:
def __init__(self):
self.main_window = tkinter.Tk()
self.name = tkinter.Label(self.main_window, text="test widget", underline=2)
self.name.pack()
self.infobutton = tkinter.Button(
self.main_window, text="click it", command=self.info)
self.infobutton.pack()
self.invoer = tkinter.Entry(self.main_window, width=10)
self.invoer.pack()
self.value = tkinter.StringVar()
self.value_label = tkinter.Label(self.main_window, textvariable=self.value)
self.value_label.pack()
tkinter.mainloop()
def info(self):
tekst = self.invoer.get()
self.value.set(tekst)
if __name__ == "__main__":
GUI()
Radio buttons and Check boxes
This part will explain Radio buttons and check boxes and how they work.
Radio buttons
The Radio button is a standard Tkinter widget used to implement one-of-many selections. Radiobuttons can contain text or images, and you can associate a Python function or method with each button. When the button is pressed, Tkinter automatically calls that function or method.
RadioButton(parent, options)
- Parent = This parameter is used to represent the parent window.
- Options = There are a few options for this function, I have listed the ones I have found below. They can be written in key-value pairs and can be separated by commas. (some of these are my own interpretation and might not be correct, they will be marked with a #)
- Text = Text displayed on the button.
- Variable = How much space the buttons can take up in the window/frame. #
- Value = How many buttons the function should create. #
Radio buttons can be designed in many different ways. two examples are:
- The standard radio buttons:
# Importing Tkinter module
from tkinter import *
from tkinter.ttk import *
# Creating master Tkinter window
master = Tk()
master.geometry("175x175")
# Tkinter string variable
# able to store any string value
v = StringVar(master, "1")
# Dictionary to create multiple buttons
values = {"RadioButton 1" : "1",
"RadioButton 2" : "2",
"RadioButton 3" : "3",
"RadioButton 4" : "4",
"RadioButton 5" : "5"}
# Loop is used to create multiple Radiobuttons
# rather than creating each button separately
for (text, value) in values.items():
Radiobutton(master, text = text, variable = v,
value = value).pack(side = TOP, ipady = 5)
# Infinite loop can be terminated by
# keyboard or mouse interrupt
# or by any predefined function (destroy())
mainloop()
- Radio buttons in the form of blue boxes, this code is the same except for the indicator and background options at the radiobutton function:
# Importing Tkinter module
from tkinter import *
# from tkinter.ttk import *
# Creating master Tkinter window
master = Tk()
master.geometry("175x175")
# Tkinter string variable
# able to store any string value
v = StringVar(master, "1")
# Dictionary to create multiple buttons
values = {"RadioButton 1" : "1",
"RadioButton 2" : "2",
"RadioButton 3" : "3",
"RadioButton 4" : "4",
"RadioButton 5" : "5"}
# Loop is used to create multiple Radiobuttons
# rather than creating each button separately
for (text, value) in values.items():
Radiobutton(master, text = text, variable = v,
value = value, indicator = 0,
background = "light blue").pack(fill = X, ipady = 5)
# Infinite loop can be terminated by
# keyboard or mouse interrupt
# or by any predefined function (destroy())
mainloop()
Check Boxes
The Checkbutton widget is a standard Tkinter widget that is used to implement on/off selections. Checkbuttons can contain text or images. When the button is pressed, Tkinter calls that function or method.
tkinter.Checkbox(parent, options)
- Parent = This parameter is used to represent the parent window.
- Options = There are a few options for this function, I have listed the ones I have found below. They can be written in key-value pairs and can be separated by commas.
- activebackground = This option used to represent the background color when the checkbutton is under the cursor.
- activeforeground = This option used to represent the foreground color when the checkbutton is under the cursor.
- bg = This option used to represent the normal background color displayed behind the label and indicator.
- bitmap = This option used to display a monochrome image on a button.
- bd = This option used to represent the size of the border around the indicator and the default value is 2 pixels.
- command = This option is associated with a function to be called when the state of the checkbutton is changed.
- cursor = By using this option, the mouse cursor will change to that pattern when it is over the checkbutton.
- disabledforeground = The foreground color used to render the text of a disabled checkbutton. The default is a stippled version of the default foreground color.
- font = This option used to represent the font used for the text.
- fg = This option used to represent the color used to render the text.
- height = This option used to represent the number of lines of text on the checkbutton and it’s default value is 1.
- highlightcolor = This option used to represent the color of the focus highlight when the checkbutton has the focus.
- image = This option used to display a graphic image on the button.
- justify = This option used to control how the text is justified: CENTER, LEFT, or RIGHT.
- offvalue = The associated control variable is set to 0 by default if the button is unchecked. We can change the state of an unchecked variable to some other one.
- onvalue: The associated control variable is set to 1 by default if the button is checked. We can change the state of the checked variable to some other one.
- padx = This option used to represent how much space to leave to the left and right of the checkbutton and text. It’s default value is 1 pixel.
- pady = This option used to represent how much space to leave above and below the checkbutton and text. It’s default value is 1 pixel.
- relief = The type of the border of the checkbutton. It’s default value is set to FLAT.
- selectcolor = This option used to represent the color of the checkbutton when it is set. The Default is selectcolor=“red”.
- selectimage = The image is shown on the checkbutton when it is set.
- state = It represents the state of the checkbutton. By default, it is set to normal. We can change it to DISABLED to make the checkbutton unresponsive. The state of the checkbutton is ACTIVE when it is under focus.
- text = This option used use newlines (“\n”) to display multiple lines of text.
- underline = This option used to represent the index of the character in the text which is to be underlined. The indexing starts with zero in the text.
- variable = This option used to represents the associated variable that tracks the state of the checkbutton.
- width = This option used to represents the width of the checkbutton. and also represented in the number of characters that are represented in the form of texts.
- wraplength = This option will be broken text into the number of pieces.
(dia 24 tot 26)