Exercise 203

Using the Tkinter Python library, write a Python program that displays a dialog asking the user to enter their name and their age and return the message:
- Hello followed by his name
- You are major ! age if the age entered is > = 18
- You are minor ! if the age entered is > 18

Solution

from tkinter import *

# method that performs the action
def action ():
# getting the user name
name = entryName.get ()

# Getting the user age
age = int(entryAge.get())
# Testing age value
if age < 18:
lblResult['text'] = "Welcome : " + name + " You are minor ! "
else :
lblResult['text'] = "Welcome : " + name + " You are major ! "

# creation of the main window
root = Tk ()
root.geometry ("475x200")

# Creation of the first entry input field with the associated label
lblName = Label (root, text = "Enter your name")
lblName.place (x = 50, y = 20)
entryName = Entry (root)
entryName.place (x = 230, y = 20 , width = 200)

# Create a label and an entry to get age value
lblAge = Label (root, text = "Enter your age :")
lblAge.place (x = 50, y = 50)
entryAge = Entry (root)
entryAge.place (x = 230, y = 50 , width = 200)

# Create a label to display result
lblResult = Label (root, text = "..............................................")
lblResult.place (x = 230, y = 80)
# Creatie a button that validates the action
Validate = Button (root, text = "Validate", command = action)
Validate.place (x = 230, y = 120, width = 200)

root.mainloop ()

Younes Derfoufi
my-courses.net

Leave a Reply