GUI Programming with Python Tkinter PDF

Summary

This document provides an introduction to GUI programming using Python's Tkinter library. It covers fundamental concepts, widgets, and their use in creating user interfaces. The document focuses on the Tkinter module for implementing various user interface elements.

Full Transcript

SHAQRA UNIVERSITY College of Computing and Information Technology Programming Language (2) CSC 213 GUI Programming with Python Tkinter What Is A GUI? Graphical User Interface(GUI) is a form of user interface which allows users to interact with computers through...

SHAQRA UNIVERSITY College of Computing and Information Technology Programming Language (2) CSC 213 GUI Programming with Python Tkinter What Is A GUI? Graphical User Interface(GUI) is a form of user interface which allows users to interact with computers through visual indicators using items such as icons, menus, windows, etc. Every time you interact with the screen on your computer or your phone you are more than liking using a graphical user interface, or GUI (pronounced gooey). Those dazzling rectangular windows with buttons, icons, and menus were created for us to have a much easier way to interact with our electronic devices. Older methods, such as MS-DOS, used the command line and text. While Python has a number of toolkits for making your own GUIs, Tkinter is good for learning the basics about UI development. We'll focus on making our own GUIs using Python and the Tkinter module. We'll begin by going over some of the basics creating an interface's window and learning how to display images and text So that you can work towards thinking of ideas for how you can create your own applications. What Is Tkinter? Tkinter is Python's standard GUI package. It is an object-oriented layer on top of the open-source Tcl/Tk widget toolkit. While there are more feature complete packages available for creating a GUI, such as PyQt, Tkinter remains popular as it is simple, widely used by beginners and has a ton of references to get you started. What are Widgets? Widgets in Tkinter are the elements of GUI application which provides various controls (such as Labels, Buttons, ComboBoxes, CheckBoxes, MenuBars, RadioButtons and many more) to users to interact with the application. Fundamental structure of tkinter program Basic Tkinter Widgets: Creating A Window Let's start with the most basic idea: creating a window. It's really quite simple using Tkinter. Let's create a new file called basic_window.py And that's it. Not very interesting... yet. The first line imports all of the functions for the module Tkinter. root in line 2 tends to be the standard name for initializing the Tk root widget (that, or master). The root widget, which is the main window and our parent window, has to be created before any other windows. Also, there can be only one root. Finally, the last line runs the main event loop. Geometry Management Creating a new widget doesn’t mean that it will appear on the screen. To display it, we need to call a special method: either grid, pack(example above), or place. Next, let's take a look at how to make some adjustments to our root window. In lines 4-8, we are able to call on methods related to the root window. In line 4, we can change the title of the window. You can also change the background color of the window, shown in line 5. We can also adjust the size of a window. We set the minimum size (line 6) and maximum size (line 9) for the window. Finally, let's talk about geometry(). Simply put, geometry allows us to consider how the window will look when we first run the program. We can set the starting size of the window as well as where it will first appear on the screen by specifying the width, height, x, and y coordinates. If the x and y coordinates aren't set, then the window will show up in the top-left corner, (0,0), of the screen. Creating A Label In Tkinter, you can use widgets to give your GUIs various properties and functionalities. Labels are the most basic widget and can display either text or images. Let's take a look at the above code. First, we import the Tkinter module and then set up the main window and it's parameters. In line 9, we create a Label widget for displaying text. The first parameter is our root window, followed by the text that we want to display. The pack() method that is called on text in the next line is used to fit the size of the window to the text (it "packs" a widget in the parent window). Also, if we adjust the window size the label will stay in the top-center part of the window. There are other ways to position a label or other widgets in different areas, including place() and grid(). There are a few ways to load images in Tkinter. For this example, we'll see how to do it with a Label widget. In line 9, we make a call to the PhotoImage class to load the image file we want to use. You can pass your own image file to PhotoImage. The Label widget is called, but the text parameter is changed to the image we want to display. The PhotoImage class can only load GIF and PGM/PPG image formats. What is important to notice here is the way that the pack() method displays the text and images. Each Label is placed in the parent window in an optimized way. We can also specify the relative positions of the widgets using pack(). Experiment by adding your own images or text and see how it changes the window. Use Tkinter To Design GUI Layout create a simple and structured layout using the Frame widget, Tkinter and Python Plan The Layout Below is a simple idea for what kind of window we will make in this tutorial. Planning before we get started can help us think about where our widgets and frames will go. Frame Widget Organizing the GUI is made possible and easier with the Frame widget. Frames are like boxes or mini-windows within the parent window -- self-contained areas that each contain their own grids, so adding widgets to them is super easy. Nesting frames is even an option if needed. To add a frame into the root window, create a Frame1 widget as seen in line 8. Let's look at the Frame parameters. We set left_frame as part of the root window. Then, specify the width and height. It is important to note that the frames will resize to whatever has been put inside of them. For example, if you display a small label inside the frame, then the frame will adjust to the label's size. Next, we place left_frame in the main window using grid(). Grid is another layout method in Tkinter for organizing widgets. You can think of grid like an Excel spreadsheet. Each "cell" has a row number and a column number. We can assign different widgets in the window by specifying the values. So the frame up above is in (row 0, column 0). The other two parameters, padx and pady, specify the amount of padding around the widget in pixels. Frame In Frame Now, let's take a quick look at adding a frame within the larger frame. Be sure to focus on the row numbers below and see if their order makes sense. Create A Simple GUI Layout we want to add other frames and widgets into our window. The following is a simple example of a better organized GUI with label widgets. While it is not aesthetically pleasing yet, it is functioning properly. from tkinter import * root = Tk() # create root window root.title("Basic GUI Layout") # title of the GUI window root.maxsize(900, 600) # specify the max size the window can expand to root.config(bg="skyblue") # specify background color # Create left and right frames left_frame = Frame(root, width=200, height=400, bg='grey') left_frame.grid(row=0, column=0, padx=10, pady=5) right_frame = Frame(root, width=650, height=400, bg='grey') right_frame.grid(row=0, column=1, padx=10, pady=5) # Create frames and labels in left_frame Label(left_frame, text="Original Image").grid(row=0, column=0, padx=5, pady=5) # load image to be "edited" image = PhotoImage(file="hem.gif") original_image = image.subsample(3,3) # resize image using subsample Label(left_frame, image=original_image).grid(row=1, column=0, padx=5, pady=5) # Display image in right_frame Label(right_frame, image=image).grid(row=0,column=0, padx=5, pady=5) # Create tool bar frame tool_bar = Frame(left_frame, width=180, height=185) tool_bar.grid(row=2, column=0, padx=5, pady=5) # Example labels that serve as placeholders for other widgets # ipadx is padding inside the Label widget Label(tool_bar, text="Tools", relief=RAISED).grid(row=0, column=0, padx=5, pady=3, ipadx=10) Label(tool_bar, text="Filters", relief=RAISED).grid(row=0, column=1, padx=5, pady=3, ipadx=10) # Example labels that could be displayed under the "Tool" menu Label(tool_bar, text="Select").grid(row=1, column=0, padx=5, pady=5) Label(tool_bar, text="Crop").grid(row=2, column=0, padx=5, pady=5) Label(tool_bar, text="Rotate & Flip").grid(row=3, column=0, padx=5, pady=5) Label(tool_bar, text="Resize").grid(row=4, column=0, padx=5, pady=5) Label(tool_bar, text="Exposure").grid(row=5, column=0, padx=5, pady=5) root.mainloop() A few things to note: To use a different image to display, change the name of the file passed to the file parameter in line 18. The subsample() method in line 19 reduces the scale of the image by only using every x and y number of pixels. So, it will reduce the image by skipping pixels. Create Buttons In Tkinter With any button in real-life, the purpose of pushing it is to perform some action, to actually do something. Push the button on the TV remote, the TV turns on. Click the 'X' button at the top-corner of this window and you will close it. It's the same for buttons in Tkinter. Push the button and maybe display some text, or maybe call another function and perform some action. We can use the Button widget to create a very basic TV remote in the following code. In line 5, we make a button object from the Button class. Its first parameter is the main window and that is followed by the the text we want to display on the button, "ON". Then in line 6 we pack() the button in the root window. We create the turn_off, vol_up, and vol_down buttons in similar fashions and pack() them in the window. However, only one of these buttons, turn_off, does anything at the moment. We can use the keyword command to make the button call a function. root.quit() closes the root window. From here we can look at adding functions to each of our buttons and learning how to alter their appearances. RadioButton in Tkinter | Python The Radiobutton 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. Changing button boxes into standard radio buttons. For this remove indicatoron option. Checkbutton in Tkinter | Python 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. Canvas in Tkinter | Python The Canvas widget lets us display various graphics on the application. It can be used to draw simple shapes to complicated graphs. We can also display various kinds of custom widgets according to our needs. Syntax: C = Canvas(root, height, width, bd, bg,..) Some common drawing methods: Creating an Oval oval = C.create_oval(x0, y0, x1, y1, options) Creating an arc arc = C.create_arc(20, 50, 190, 240, start=0, extent=110, fill="red") Creating a Line line = C.create_line(x0, y0, x1, y1,..., xn, yn, options) Creating a polygon oval = C.create_polygon(x0, y0, x1, y1,...xn, yn, options) Combobox in Tkinter | Python Combobox is a combination of Listbox and an entry field. It is one of the Tkinter widgets where it contains a down arrow to select from a list of options. It helps the users to select according to the list of options displayed. When the user clicks on the drop-down arrow on the entry field, a pop up of the scrolled Listbox is displayed down the entry field. The selected option will be displayed in the entry field only when an option from the Listbox is selected. # Shows february as a default value monthchoosen.current(1) window.mainloop() Entry in Tkinter | Python The Entry Widget is a Tkinter Widget used to Enter or display a single line of text. Text in Tkinter | Python Text Widget is used where a user wants to insert multiline text fields. This widget can be used for a variety of applications where the multiline text is required such as messaging, sending information or displaying information and many other tasks. We can insert media files such as images and links also in the Text widget. Syntax: T = Text(root, bg, fg, bd, height, width, font,..) # Create text widget and specify size. T = Text(root, height = 5, width = 52) Saving Text and performing operations Message in Tkinter | Python The Message widget is used to show the message to the user regarding the behavior of the python application. The message text contains more than one line. Syntax: The syntax to use the message is given below. w = Message( master, options) Menu in Tkinter | Python Menus are the important part of any GUI. A common use of menus is to provide convenient access to various operations such as saving or opening a file, quitting a program, or manipulating data. Toplevel menus are displayed just under the title bar of the root or any other toplevel windows. Note: In above application, commands are set to None but one may add different commands to different labels to perform the required task. Spinbox in Tkinter | Python The Spinbox widget is used to select from a fixed number of values. It is an alternative Entry widget and provides the range of values to the user. Scrollbar in Tkinter | Python The scrollbar widget is used to scroll down the content. We can also create the horizontal scrollbars to the Entry widget. ListBox in Tkinter | Python The ListBox widget is used to display different types of items. These items must be of the same type of font and having the same font color. The items must also be of Text type. The user can select one or more items from the given list according to the requirement. Syntax: listbox = Listbox(root, bg, fg, bd, height, width, font,..) # Delete Items from the list by specifying the index. listbox.delete(2) #create bottun from tkinter import * from tkinter import ttkroot=Tk() button1=ttk.Button(root,text='Click')button1.pack() button2=ttk.Button(root,text='Click')button2.pack() button3=ttk.Button(root,text='Click')button3.pack() def buClick(x): print('Clicked:()'.format(x)) button1.config(command=lambda: buClick(1)) button2.config(command=lambda: buClick(1))button3.config(command=lambda: buClick(1)) enrty1=ttk.Entry(root,width=50)enrty1.pack() root.mainloop() #to design a bottun from tkinter import * from tkinter import ttk root=Tk()b1=ttk.Button(root,text='‫)'تسجيل دخول‬ b1.pack() style=ttk.Style() style.theme_use('clam') style.configure('TButton',background='dark green',foreground='white', font=('Times new roman',30,'bold'ipadx=50,ipady=50)) #for specific bottun style.configure('info.TButton',font=('Calibri Light',30,'bold'))b2.configure(style='info.TButton') #to move bottun in specific placement from tkinter import * from tkinter import ttk root = Tk()style = ttk.Style() style.theme_use('clam') L1=ttk.Label(root,background='brown',text='black').grid(row=0,column=0,sticky='snew' ) L2 = ttk.Label(root,background='light pink',text='purple').grid(row=0,column=1,sticky='snew') L3=ttk.Label(root,background='light blue',text='blue').grid(row=1,column=0,columnspan=2,sticky='snew') L4 = ttk.Label(root,background='purple',text='orange').grid(row=0,column=2,rowspan=2,sticky='snew',ipadx=10,ipady=10) #if i wanna move the word from the button use it VERY IMPORTANT ipadx=10,ipady=10 #to design the bottun #to design the bottun from tkinter import *from tkinter import ttk root = Tk() style = ttk.Style()style.theme_use('clam') L1=ttk.Label(root,background='brown',text='black').grid(row=0,column=0 ,sticky='snew') L2 = ttk.Label(root,background='light pink',text='purple').grid(row=0, column=1,sticky='snew') L3=ttk.Label(root,background='light blue',text='blue').grid(row=1,column=0, columnspan=2,sticky='snew') L4 = ttk.Label(root,background='purple',text='orange').grid(row=0,column=2 ,rowspan=2,sticky='snew',ipadx=10,ipady=10,padx=15) root.rowconfigure(0,weight=1) root.rowconfigure(1,weight=1)root.columnconfigure(0,weight=1) root.columnconfigure(1,weight=1)root.columnconfigure(2,weight=1) #if i wanna move the word from the button use it VERY IMPORTANT #ipadx=10,ipady=10 # if we want to move the whole bottun#padx=15 (PAD) is the sectret from tkinter import *from tkinter import ttk root = Tk() style = ttk.Style() style.theme_use('clam') L1=ttk.Label(root,background='brown',text='black').grid(row=0,column=0,sticky='snew')L2 = ttk.Label(root,background='light pink',text='purple').grid(row=0,column=1,sticky='snew') L3=ttk.Label(root,background='light blue',text='blue').grid(row=1,column=0,columnspan=2,sticky='snew') L4=ttk.Label(root,background='purple',text='orange').grid(row=0,column=2,rowspan=2,sticky='sne w',ipadx=10,ipady=10,padx=15) root.rowconfigure(0,weight=1) root.rowconfigure(1,weight=1)root.columnconfigure(0,weight=1) root.columnconfigure(1,weight=1)root.columnconfigure(2,weight=1) #if i wanna move the word from the button use it VERY IMPORTANT #ipadx=10,ipady=10 # if we want to move the whole bottun#padx=15 (PAD) is the sectret #to design the frame from tkinter import *from tkinter import ttk root = Tk()f1=ttk.Frame(root) f1.pack()f1.config(width=200,height=200,relief=RIDGE) f2=ttk.Frame(root)f2.pack() f1.config(width=200,height=200,relief=RIDGE)ttk.Button(f1,text='bottun1').grid(row= 0,column=0) ttk.Button(f1,text='bottun2').grid(row=0,column=3)ttk.Button(f2,text='bottun3').pack() ttk.Button(f2,text='bottun4').pack()ttk.Button(f2,text='bottun5').pack() f1.config(padding=(10,10))ttk.LabelFrame(root,height=10,width=10,text='login').pack () f3=ttk.LabelFrame(root,height=100,width=100,text='login').pack() #rid is for the fisrt frame, the second is for pack(), easier and prettier#f1.config(padding=(10,10)), ‫ الفريمات يعني زي اللي يحط خط بينهم مهم مرره‬9‫يفرق ب‬ ‫سويه اذا كان الحساب سجل مسبقا‬# from tkinter import * from tkinter import ttkroot = Tk() cb=ttk.Checkbutton(root,text='is he married?')cb.pack() state=StringVar()state.set('yes') state.get()cb.config(variable=state,onvalue='yes he is',offvalue='no he is not') state.get()rb1=ttk.Radiobutton(root,text='male') rb1.pack()rb2=ttk.Radiobutton(root,text='female') rb2.pack()rbvalue=StringVar() rb1.config(variable=rbvalue, value='male')rb2.config(variable=rbvalue, value='female') rbvalue.get()ttk.Radiobutton(root,text='is he married?',variable=rbvalue,value='male').pack() #maybe i need it from tkinter import * from tkinter import ttk root=Tk() def key_press(event): print('type:{}'.format(event.type)) print('Ctrol+C') root.bind('',key_press) def button_press(event): print('button is pressed') bu=ttk.Button(root,text='Click here!') bu.pack() bu.bind('',button_press) def buClick(x): print('Clicked:{}',format(x))

Use Quizgecko on...
Browser
Browser