0% found this document useful (0 votes)
16 views100 pages

Year78Part1_88ffcbe7e3aa48309d770dea2bf73440 (3)

This document provides an introduction to Python 3, covering its features, installation, and usage of the IDLE IDE. It explains the different programming modes (interactive and script), the turtle graphics module, and basic programming concepts such as variables, data types, and arithmetic operators. Additionally, it highlights the importance of modules and provides examples of tasks and programming exercises for learners.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views100 pages

Year78Part1_88ffcbe7e3aa48309d770dea2bf73440 (3)

This document provides an introduction to Python 3, covering its features, installation, and usage of the IDLE IDE. It explains the different programming modes (interactive and script), the turtle graphics module, and basic programming concepts such as variables, data types, and arithmetic operators. Additionally, it highlights the importance of modules and provides examples of tasks and programming exercises for learners.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 100

Python

Python 3 (Getting Python 3 and IDLE)


Objectives Week 1
• Identify and know how to use simple interactive development environment to
support your program

• Discuss and demonstrate how to use interactive mode and script mode in python

• Explain how to program and save a text-based application in script mode

• Know how to use built-in turtle module


Introduction to Python
• Python is a modern, powerful programming language used by many organisations such as YouTube,
Wikipedia, Google, Dropbox, CERN and NASA
• Python 3 is the latest version of the Python programming language. It is a loosely typed script
language.
• Loosely typed means that it is usually not necessary to declare variable types; the interpreter looks
after this.
• A compiler converts instructions into machine code that can be read and executed by a computer.
• Script languages do not have a compiler. This means that, in general, Python programs cannot run
as quickly as compiled languages. However, this brings numerous advantages such as fast and agile
development.
Introduction to Python
Getting Python 3 and IDLE
• There are Python 3 installers for most types of computer available on the python.org website. You
should choose the latest stable version of Python 3
• Python comes with a perfectly good IDE called IDLE. Starting up IDLE will enable you to run a
program straight away.
• An Integrated Development Environment (IDE) is a piece of software that is similar to a word
processor but for writing programs.
• IDEs provide special tools that help programmers do their jobs more efficiently. They usually have an
easy way of running the programs during the development stage - such as a Run button. There are
many IDEs that can be used with Python.
• IDLE(integrated development and learning environment): is a software that provides features for
creating, editing and running programs.
Introduction to Python
Getting Python 3 and IDLE Getting Python 3 and IDLE
Python Shell • In this session we will refer to typing code
into the shell as an ‘interactive session’.
• Interactive sessions are great for
experimenting and trying out new things that
you learn about Python.

• This window shows the Python shell, which is the


first thing that opens when you start IDLE. This is
an unusual feature in Python.
• In the shell, we can write Python commands and
code snippets and run them without having to
save a file.
Introduction to Python
Getting Python 3 and IDLE
• You have now run your first interactive mode program. Your code told the computer to print the
text ‘Hello world!’ to the screen. It executed your code when you pressed the return key on your
keyboard.
• You can also use interactive mode as a simple calculator. Try entering this sum and press return:
>>> 3*4
• Note: Interactive sessions are used to illustrate simple concepts or to show the correct use of
some new syntax.
• Sometimes we want to save our programs; this is not possible in the Python shell. To do this we
open a file, type in our code and then save the file with a .py extension.
Introduction to Python
IDLE windows /modes Uses of Interactive mode
1. Interactive mode • Write Python commands and code snippets
• Run code snippets without having to save a file.
• This is where any output appears.

2. Script mode
2. Script mode • We can save the file with a .py extension
• To open a new file for programming in script mode
you click on File and then New File
• Then, save it to your Documents folder and run
your program by selecting Run Module from the
Run menu or pressing F5 on your keyboard.
Other Integrated Development Environments (IDEs)
Other types of IDEs
1. Thonny (contains both a Python shell and a script area in a single window)
2. Wing IDE 101
3. IDLE
Turtle Graphics

• Python has a special built-in module that we can use to create programs that draw patterns. This is an
implementation of the turtle graphics part of the Logo programming language.
• The great thing about this module is that the simple turtle commands can be combined with Python
code. This means that, as we learn more about Python, we will be able to make more sophisticated
and interesting turtle programs.
What is a turtle?
• A turtle is a robot that can be programmed to draw a line by following a path and placing a pen on the
floor to create a line.
A floor Turtle
Turtle Graphics

• The language that is used to control the robot consists of simple directional commands and is based
on the Logo programming language.
• There are many online sites and applications that allow users to control an onscreen turtle by using he
Logo programming language.
A few commands for a floor turtle
Turtle Graphics

DEMO TASK DEMO TASK


Draw a square Draw a triangle
• Using Python’s turtle module, write a program that Open your preferred IDE and write, save
draws a square. and run a turtle program that draws an
Solution equilateral triangle.
• First write a line of code that imports the turtle module
into our program.
Turtle Graphics

• Python 3 comes with many commands that are ready to use – for example, print () and input ().
• There is also a large library of other commands we can use if we import one of the many built-in
modules that come with the standard install.
Example of Python built-in modules
1. Turtle
2. tkinter
There are different ways of importing these modules. How you import them affects the way you have
to write your commands.
Different ways of importing modules
• the turtle module is imported with the following line of code: From turtle import *
Turtle Graphics

Different ways of importing modules


• the turtle module is imported with the following line of code:
From turtle import *
• The * (asterisk) stands for everything. It means, ‘import every command available in the turtle
module’.
import tkinter
• The tkinter module gives us access to a lot of graphical programming tools.
• When importing a module with this syntax, we have to use different syntax to call the turtle
commands.
• When we import tkinter like this, we have to precede the tkinter commands with the name of the
module and a dot like this: tkinter.mainloop()
Turtle Graphics

Different ways of importing modules


Graphical user interface (GUI) applications
Graphical user interface (GUI) application
• Python scripts are not limited to text-based applications. By importing the tkinter module, it is easy to
produce visually rich graphical user interfaces (GUIs) and attach your algorithms to buttons in windows.
SUMMARY
• Python 3 is a loosely typed programming language that is designed to encourage easily read code.
• Python 3 comes with a simple Integrated Development Environment called IDLE. There are many other
IDEs available, such as Thonny and Wing IDE 101, both of which are specifically designed for students.
• There are three main styles of programming in Python 3:
1. interactive mode: quick tests and trials that can be programmed in the Python shell
2. script mode: text-based scripts that can be saved so that your applications can be reused
3. GUI applications: full, visually rich applications that can be produced in script mode.
• There is a large library of specialist modules that come with Python and can be imported into your
programs such as the turtle and tkinter modules
End of chapter Test
1.In your preferred IDE, write a text-based program that asks users to input their age and then their
name. Your program should then output a phrase similar to: ‘Hi Vipul. You are 16.”

2.Write a turtle program that draws the house shown here:

3 Write a turtle program that draws a regular pentagon with sides of length 100 pixels.
Topic

Variables and arithmetic operators


Objectives Week 2

• Declare and use variables and constants

• Use the data types Integer, Real, Char, String and Boolean

• Use basic mathematical operators to process input values

• Design and represent simple programs using flowcharts and pseudocode

• Write simple Python programs that can be run and debugged

• How to generate random numbers and round decimals.


Variables and arithmetic operators
Introduction
• Programs need to store information. This information is stored in variables. The information stored
can be numbers or text.
• The values stored in variables may need to be updated as a program is run or used to calculate
new data.
• To do this you can use simple mathematical operators such as addition, subtraction etc.
• This session explains how to use variables and mathematical operators when designing and writing
Python programs.
Variables and arithmetic operators
• Variable is a space in the computer memory where we can store data: strings, integer etc.
Variables are used to store data in a program. When writing programs, you will use variables or
constants to refer to these data values.
• A variable identifies data that can be changed during the execution of a program.
Variables and arithmetic operators
• Variable is a space in the computer memory where we can store data: strings, integer etc.
Variables are used to store data in a program. When writing programs, you will use variables or
constants to refer to these data values.
• A variable identifies data that can be changed during the execution of a program.

Types of data
• The data type is used by the computer to allocate a suitable location in memory.
How can we know what data type has been allocated by Python in our programs?
• To find out the data type of a variable or constant being used in a Python program, use the built-in
type () function.
Variables and arithmetic operators
Types of data
Variables and arithmetic operators
Types of data
Variables and arithmetic operators
Pseudo numbers
• Pseudo numbers are a collection of digits used to uniquely identify an item. They are not intended
to be used in calculations. They contain spaces or start with a zero.
• Pseudo numbers are normally stored in a String variable. If you store a mobile phone number as
an integer, any leading zeroes will be removed, while spaces and symbols are not permitted.
Examples of pseudo numbers
• Telephone numbers
• ISBN numbers
Variables and arithmetic operators
Naming conventions in Python
There are a variety of naming conventions in Python. Here are a few of them.
Things to consider when stating a variable names
• Use all lower case, starting with a letter and joining words with underscores. It is considered
good practice to use descriptive names. This aids readability and reduces the need for so much
commenting.

• Commenting is where the programmer writes notes in the program that the computer ignores. In
Python these start with the # symbol.
• In pseudocode, comments are preceded with two slashes (//)
Variables and arithmetic operators
Naming conventions in Python
Constants
• Constants are values that do not vary(change). Constants are used for data values that remain
fixed and keep the same value throughout our programs.
Things to consider when stating a constant
• Use all upper case characters to indicate constants.
Variables and arithmetic operators
Arithmetic operators
There are a number of operations that can be performed on numerical data in your programs.
Variables and arithmetic operators
Arithmetic operators
Variables and arithmetic operators
Arithmetic operators
Variables and arithmetic operators
Programming task
Variables and arithmetic operators
Solution to Programming task
• First we need to design the algorithm. Either with flowchart or pseudocode

Flowchart Pseudocode

Note: In Python, assignment is indicated by the use of the = symbol. In pseudocode, the <-- is used.
Variables and arithmetic operators
Note:
• To send a message to the user and collect their keyboard input, use Python’s input () function
• The input () function only returns string data types, so if we need to do calculations on numbers
supplied by the user, we will have to cast the string into an integer by using the int () function. For
example:
• age = int(input('How old are you?’))
Converting Demo task flowchart and pseudocode into python codes
# Initialize a variable to keep track of the result
result = 0
# Request and store user input
numberl = int (input('Please insert first number: '))
number2 = int (input('Please insert second number: '))
result = numberl * number2
Variables and arithmetic operators
# Display the value held in the variable result
print('The answer is ', result)
# End nicely by waiting for the user to press the return key.
input ('\n\nPress RETURN to finish.’)
Python modules
Python modules
• Python has lots of libraries of other code you can use in your programs. These are called modules.
• There are many built-in modules that have been made by other programmers around the world that you can
use and, of course, you can make your own.
• To access the tools in these modules, we first have to import them.
• // To import everything from the turtle library we use
From turtle import *
turtle(100)
However, It is safer to import your modules in the following way:
import turtle
This still gives your programs access to all the tools in this module but it now requires you to add turtle.
to all your commands.
Python modules
Python Turtle
turtle. forward(100)
Python modules
Python Turtle
Python modules
Python Turtle
To give the turtle direction

Steps to draw objects


To Move turtle 1. Import the turtle module
• Forward/ FD 2. Create turtle object from turtle class
• 3. Give turtle name of your choice
Backward/back/BK
• t.forward(100)
Python modules
Python Turtle
When you need help about how a module works type:
Help(turtle.forward)
Left and right is used to specify the angle the turtle should turn
• t.left( 45)
• t.right (45)
Note: t.Setheading and left/ right perform the same function but the angle direction may not be the same
Python modules
Python Turtle coordinate Change the shape of turtle

Other turtle shapes in the module


'arrow', 'turtle', 'circle', 'square', 'triangle', 'classic’
You can find this at:
import turtle
help(turtle.shape)
To give different line color and turtle color
Ibas.color(“ red”, “blue”)
Python modules
Steps to draw objects To change screen background colour
1. Import the turtle module wn= turtle.Screen()
2. Create turtle object from turtle class Wn.bgcolor(“black”)
3. Give turtle name of your choice
To change the shape of the turtle
To change the shape of the turtle Import turtle
Import turtle ibas = turtle.Turtle()
ibas = turtle.Turtle() ibas.shape()
ibas.shape() ibas.shape(“turtle”)
ibas.shape(“turtle”)
Python modules
Using RGB color mode (red green blue) To insert a picture
Turtle.colormode() import turtle
Turtle.colormode(255) adwoa = turtle.Turtle()
Wn.bgcolor(50, 100, 30) wn = turtle.Screen()
wn.bgpic("chief1.gif")
To rename title bar adwoa.forward(100)
wn.title(“chief justice”) wn.bgcolor("blue")

Note:
• picture should be in the same folder of the
python file
• Convert picture into gif format
• Use paint program or any picture editing program
Python modules
Python Turtle forward(100)/forward(-75)
Meaning /Help on function forward in module turtle:
• forward(distance)
• Move the turtle forward by the specified distance.
• Aliases: forward | fd
What you are to put inside the two brackets ()
Argument:
• distance -- a number (integer or float)
• Move the turtle forward by the specified distance, in the direction the turtle is headed.
Python modules
To draw a circle
Syntax
circle(radius, extent=None, steps=None)
• The center is radius units left of the turtle;
• extent - an angle - determines which part of the circle is drawn. If extent is not given, draw the
entire circle. If extent is not a full circle, one endpoint of the arc is the current pen position.
• Draw the arc in counterclockwise direction if radius is positive, otherwise in clockwise direction.
• call: circle(radius) ------------------------ # full circle
--or: circle(radius, extent) ---------------- # arc
--or: circle(radius, extent, steps)
--or: circle(radius, steps=6)---------------- # 6-sided polygon
Python modules
To draw a circle

To go back or undo previous work

Example:
>>> circle(50) full circle
>>> circle(120, 180) # semicircle ------ radius and angle or extent no steps
>>> ----- radius and steps no angle
Python modules
To draw a square To draw a circle and color To draw a polygon and color
Random and Round
The random module provides functions that generate pseudorandom(random) numbers.
The function random returns a random float/decimal numbers between 0.0 and 1.0 (including 0.0 but not
1.0). Each time you call random (), you get the next number in a long series. We can assign a variable in
usual way:
my_random_number  RANDOM()
To import the random module

Note:
• This program produces the following list of 10 random numbers between 0.0 and up to but not including
1.0.
• remember python is case sensitive and the indentation
• Run the program more than once and see what numbers you get.
Random and Round
The random function is only one of many functions that handle random numbers.
The function randint takes the parameters low and high, and returns an integer between low and
high (including both).

Round function (round number to a given decimal place)


ROUND () takes two arguments: the identifier of the number we want to be rounded, and the number
of decimal places to round to (0 = integers). Putting these two functions together we can write:
my_dice_role  round(random()*10, 0)
Random and Round
SUMMARY
Topic

Algorithm design tools


Objectives
In this lesson you will:
• learn the difference between the three programming constructs: sequence, selection
and iteration
• learn how to use flowcharts and pseudocode when designing algorithms
• learn the main symbols used in flowcharts
• learn about the preferred format used in pseudocode.
Algorithm design tools
Programming Constructs
• Construct: is a method of controlling the order in which the statements in an algorithms are
executed
• Programming constructs: are programming ideas about code structure such as sequence,
selection and iteration
• Python and other procedural languages make use of three basic programming constructs.
• Combining these constructs provides a programmer with the tools required to solve logical
problems.
Three Basic Programming Constructs
• Sequence: is the order in which instructions run in algorithms and programs OR
• it is the order in which the lines of code are written, usually from top to bottom and executed(run)
OR
• is a set of commands or instructions carried out in order or the order itself
Algorithm design tools
Three Basic Programming Constructs
• The program will execute (run) the first line of code before moving to the second and subsequent
lines.
• If the instructions are in the wrong order the algorithms or programs may not work in the way you
want it to.
Algorithm design tools
Three Basic Programming Constructs
• Selection: means choosing which command to run from among the options when the code carried
out depends on the answer to a condition.
• A conditional statement is one way to use selection. A conditional statement is a section of a code
that tells your program to either run one set instructions or another set of instructions depending on
whether a condition is true or false
Algorithm design tools
Three Basic Programming Constructs
• Iteration: is the repeated execution of a set of statements using either a function that calls itself or a
loop. In scratch program we sometimes call iterators; repeat block or loop and forever loop
• In iteration the code repeats a certain sequence a number of times depending on certain condition.

• A forever loop is an iterator that will keep repeating the code forever
• A repeat block will repeat the code for a set number of times
Algorithm design tools
Design Tools
• When you design programs, it is normal to plan the logic of the program before you start to code
the solution.
• The first step in the design process is to break down the problem into smaller problems. When we
do into it is called decomposition.
• Decomposition is computational thinking skills that involves thinking about large task and
breaking them down into smaller task
• The next stage is to design an algorithm for the individual problems. Two approaches that can be
used to design algorithms are flowcharts and pseudocode.
• You will need to be able to use them to explain the logic of your solutions to given tasks.
Stages of Design Process
Algorithm design tools
Flowcharts
• Flowcharts are graphical representations of the logic of the intended system.
• They make use of symbols to represent operations or processes and are joined by lines indicating
the sequence of operations.
Algorithm design tools
Flowcharts
Algorithm design tools
Flowcharts

What is Pseudocode?
• Pseudocode is a way of describing or representing the logic and sequence of an algorithm or
program using both natural language and code-like statement.
• It uses keywords and constructs, similar to those used in programming languages, but without the
need for a strict use of syntax.
Algorithm design tools
Principles underlying the usage of Pseudocode
• Use capital letters for keywords close to those used in programming languages.
• Use lower case letters for natural language descriptions.
• Use indentation to show the start and end of blocks of code statements, primarily when using
selection and iteration.
Advantage
• One of the advantages of learning to program using Python is that the actual coding language is
structured in a similar way to natural language and therefore closely resembles pseudocode.
• Python IDEs such as IDLE, Thonny and Wing IDE also automatically indent instructions where
appropriate
Algorithm design tools
Example of Pseudocode
• The following pseudocode is for an algorithm that accepts the input of two numbers. These values
are added together and the result is stored in a memory area called answer. The value in answer is
then displayed to the user.

Note the use of the following symbols used in pseudocode


Algorithm design tools
Example of Pseudocode

Demo task: Construct a flowchart to represent the pseudocode example in Code snippet above.
Algorithm design tools
Topics

Subroutines
Objectivies
Subroutines
Introduction
Imagine you are writing a program that has 100 users who want to be able to change
their name. Imagine that to do this you had to write your code like this:
• If user1 wants to change their name:
<code that asks for user1's new name and then edits it>
• If user2 wants to change their name:
<code that asks for user2's new name and then edits it>
• If user3 wants to change their name:
<code that asks for user3's new name and then edits it> …….
• If user l00 wants to change their name:
<code that asks for userl00's new name and then edits it>
Subroutines
Introduction
• Your program would be very long and the chances of making a mistake would be high. Finding
errors would also be very tedious.
• We do not need to write code in this way. We can write one smaller program, within our larger
program, that can be called whenever any user needs to have their name changed. These smaller
programs are called subroutines.
• A subroutine is a code that performs a specific task that can be called from anywhere in the rest of
your program.
Characteristics of subroutine
All subroutines in Python require:
• An identifier (a name)
• A keyword define written as (def)
Subroutines
Introduction
For example:
def my_function():

• def: is the code that carries out the purpose of my_function


• A subroutine can then be called in the rest of the program as often as is required by its identifier.
Advantages of subroutines
1. The subroutine can be called when needed. A single block of code can be used many times in
our programs. Being able to reuse code avoids the need to repeat identical code sequences,
which shortens our programs and makes them easier to read.
2. There is only one section of code to debug. If an error is located in a subroutine, only the
individual subroutine needs to be debugged. If the code had been repeated throughout the main
program, every occurrence would need to be found and changed.
Subroutines
Advantages of subroutines
3. There is only one section of code to update. If we improve or extend our subroutine, the benefits

are available everywhere the subroutine is called in our program.


4. Button presses can be used to call various subroutines. You will learn about this in the optional

chapter.
Subroutines
Types of subroutines Types of subroutines
There are Two main types of subroutine:
1. Functions
2. procedures

• Functions: contain a mini program that can be


called by the main program. They may need to Note:
be passed some values. These are called • add_two_ numbers is the function identifier;
parameters. • a and b are the parameters
• They then return a computed value back to the • 5 and 6 are the arguments passed to the
main program. Here is a pseudocode example of function.
a program that defines a function and then calls
• Output the return value, for example:
it:
OUTPUT add_two_numbers (5, 6)
• It is common to say that a function “takes” an
argument and “returns” a result. The result is
called the return value.
Subroutines
Types of subroutines Procedure pseudocode example
• Procedures are small sections of code that
can be reused.
• They are just the same as functions, but they
do not return a value to the main program.
• In pseudocode, a procedure is named and
takes the form:
PROCEDURE ... ENDPROCEDURE

• They are called by using the CALL statement.


• The CALL statement is used to execute the
procedure.
• However, any values required by the procedure
must be passed to it at the same time:
Subroutines
PRACTICE TASK
sum
In both the function and the procedure, sum is calculated from the same two arguments.
a. What value is returned by the function add_two numbers () ?
b. What value is output by the procedure add_two numbers ()?

• Breaking problems down into smaller problems is called decomposition.


• Going through a program and pulling out common sections of code into subroutines is called
refactoring.
• If you decompose your problems and refactor your programs, you will benefit from all the
advantages that subroutines can bring to your projects.
Subroutines
• Another reason for putting sections of code into a subroutine is to hide complexity. This is called
abstraction.
• Abstraction is a computational thinking skill that involves spotting key information in a problem and
hiding unnecessary information.
• Imagine that a program required us to find the fourth highest scorer in a game. Instead of adding a lot
of complicated code to the main part of the program we could, instead, call a subroutine with a
meaningful name such as get_fourth_place_player().
• A person reading the program can see what is being done and then look up how it is being performed
if they wish to know.
Subroutines
• The syntax for defining a function in Python and then calling it is:
Subroutines
DEMO TASK

The function needs:


Subroutines
DEMO TASK
Subroutines
DEMO TASK
Subroutines
DEMO TASK
Subroutines
DEMO TASK
Subroutines
Skills Focus
Subroutines
Skills Focus
Subroutines
Skills Focus
Subroutines
Programming a procedure
• The Python code for a procedure is similar to that used for a function. Remember, however, that
procedures, just like functions, can contain parameters.
• The key difference in the syllabus definitions is that procedures do not return a value, whereas
functions return a value.
• In the interactive session below, empty brackets are used to show that no parameters are required by
the subroutine.
Subroutines
Programming a procedure
Programming a procedure
Subroutines
Programming a procedure
Subroutines
Topic

Graphical user interface (GUI) applications


Objectives
Graphical user interface (GUI) applications
Make your first application in a window with a button
• Tkinter is an example of a GUI toolkit and is provided as part of the standard library
when you install Python.
• By importing the tkinter module, it is easy to produce visually rich GUIs that use buttons
to interact with the program.
• This means you already have access to the objects and methods required to make GUI
applications.
To add these elements to your programs, you just need to do these extra tasks:
1. Import the tkinter module.
2. Create the main tkinter window.
3. Add one or more tkinter widgets to your application.
4. Enter the main event loop, which listens to and acts upon events triggered by the user.
Graphical user interface (GUI) applications
• By following these four steps, you are turning your program into an event-driven system. This
means that the whole application runs in an infinite loop. This is the main event loop referred to in
step 4 above and started by the last line of code below.
• Once the main event loop is started, the application opens in its own window. This application now
constantly ‘listens’ for user interaction, such as pressing buttons or choosing an item in a drop-
down menu.
To create this application below copy the code below into a new script and save it as hello-gui.py
into your Python code folder.
Graphical user interface (GUI) applications
Graphical user interface (GUI) applications
from tkinter import *
def change_text ():
my_label.config(text='Hello World')

window = Tk()
window.title('My Application')

my_label = Label(window, width=25, height=1, text='')


my_label.grid(row=0, column=0)

my_button = Button(window, text='Say Hi', width=10, command=change_text)


my_button.grid(row=1, column=0)

window.mainloop()
Graphical user interface (GUI) applications
When designing the layout of widgets in GUI applications, you can use the grid() method. This
organizes as many cells as you require in your window using a coordinate system.

Layout using grid() method

Note how the numbers start from zero in the top left corner of the window:

It is possible to further arrange tkinter widgets by grouping them in frames.


Graphical user interface (GUI) applications
Other tkinter widgets you can use in your applications
• These code snippets should all be added after window = Tk() and above window.mainloop()
• as indicated by the comment in the following recipe for an empty tkinter window.

Note: a recipe is another name for a piece of code that you use frequently):
Graphical user interface (GUI) applications
Other tkinter widgets you can use in your applications
Graphical user interface (GUI) applications
Other tkinter widgets you can use in your applications
Graphical user interface (GUI) applications
Other tkinter widgets you can use in your applications
Graphical user interface (GUI) applications
Other tkinter widgets you can use in your applications (Solution)
Graphical user interface (GUI) applications
Other tkinter widgets you can use in your applications (Solution)
from tkinter import *
def change_text():
my_label.config(text - gender.get())

window = Tk()
window.title('My Application')

my_label = Label (window, width=25, height=1, text='')


my_label.grid(row=0, column=0)

my_button = Button(window, text='Submit', width=10, command=change_text)


my_button.grid(row=1, column=0)
Graphical user interface (GUI) applications
Other tkinter widgets you can use in your applications (Solution)

gender = StringVar()
radiol = Radiobutton(window, text='Female', variable= gender, value='female')
radiol.grid(row=2, column=0, sticky=W)

radiol.select() # pre-selects this radio button for the user

radio2 = Radiobutton(window, text='Male', variable= gender, value='male')


radio2.grid(row=3, column=0, sticky=W)

window.mainloop ()
Graphical user interface (GUI) applications
Practice tasks:
• Study the code that inserts the radio buttons in previous slide
1. Which bit of code places them on the left side of the app?
2. How would you move them to the right side of the app?
3. Amend gender-gui. py by aligning the radio buttons to the East and see what happens when you
run it again.

Practice task:
4. Rewrite the radio button application but replace the radio buttons with a simple drop-down menu.

You might also like