Practice Exercises for Button and Input Fields

Contents

Practice Exercises for Button and Input Fields#

1#

Write event handlers print_hello() and print_goodbye() for the two buttons with labels "Hello" and "Goodbye" defined in the program template below. Pressing these buttons should print the messages "Hello" and "Goodbye", respectively, in the console. Print hello/goodbye templatePrint hello/goodbye solutionPrint hello/goodbye (Checker)


# Add "Hello" and "Goodbye" buttons

###################################################
# Student should add code where relevant to the following.

try:
    import simplegui
except ImportError:
    import simplequi as simplegui


# Handlers for buttons
def print_hello():
    print('Hello')
    
    
def print_goodbye():
    print('Goodbye')


# Create frame and assign callbacks to event handlers
frame = simplegui.create_frame("Hello and Goodbye", 200, 200)
frame.add_button("Hello", print_hello)
frame.add_button("Goodbye", print_goodbye)


# Start the frame animation
frame.start()


###################################################
# Test

print_hello()
print_hello()
print_goodbye()
print_hello()
print_goodbye()

###################################################
# Expected output from test

#Hello
#Hello
#Goodbye
#Hello
#Goodbye

2#

Given the three function print_color(), set_red(), and set_blue() in the program template below, create three buttons that print and manipulate the global variable color. Use the CodeSkulptor Docs to determine the SimpleGUI method for creating a button if needed. Register buttons templateRegister buttons solutionRegister buttons (Checker)



# Register three buttons

###################################################
# Student should add code where relevant to the following.

try:
    import simplegui
except ImportError:
    import simplequi as simplegui


# Handlers for buttons
def set_red():
    global color
    color = "red"


def set_blue():
    global color
    color = "blue"


def print_color():
    print(color)


# Create frame
frame = simplegui.create_frame("Set and print colors", 200, 200)
frame.add_button('set red', set_red)
frame.add_button('set blue', set_blue)
frame.add_button('print color', print_color)

# Start the frame animation
frame.start()


###################################################
# Test

set_red()
print_color()
set_blue()
print_color()
set_red()
set_blue()
print_color()

###################################################
# Expected output from test

#red
#blue
#blue

3#

Challenge: Given the program template below, implement four buttons that manipulate a global variable count as follows. The function reset() sets the value of count to be zero, the function increment() adds one to count, the function decrement() subtracts one from count, and the function print_count() prints the value of count to the console. Count operations templateCount operations solutionCount operations (Checker)

# GUI with buttons to manipulate global variable count

###################################################
# Student should enter their code below

try:
    import simplegui
except ImportError:
    import simplequi as simplegui

# global variables
count = 0


# Define event handlers for four buttons
def reset():
    global count
    count = 0


def increment():
    global count
    count += 1


def decrement():
    global count
    count -= 1


def print_count():
    print(count)


# Create frame and assign callbacks to event handlers
f = simplegui.create_frame('Counter', 100, 100)
f.add_button('reset', reset)
f.add_button('increment', increment)
f.add_button('decrement', decrement)
f.add_button('print count', print_count)


# Start the frame animation
f.start()


    
###################################################
# Test

# Note that the GLOBAL count is defined inside a function
reset()		
increment()
print_count()
increment()
print_count()
reset()
decrement()
decrement()
print_count()

####################################################
# Expected output from test

#1
#2
#-2

4#

Write a program that creates an input field and echoes input to that field to the console. Echo templateEcho solutionEcho (Checker)


# Echo an input field

###################################################
# Student should add code where relevant to the following.

try:
    import simplegui
except ImportError:
    import simplequi as simplegui


# Handlers for input field
def get_input(inp):
    print(inp)


# Create frame and assign callbacks to event handlers
frame = simplegui.create_frame("Echo input", 200, 200)
frame.add_input('input', get_input, 100)

# Start the frame animation
frame.start()


###################################################
# Test

get_input("First test input")
get_input("Second test input")
get_input("Third test input")

###################################################
# Expected output from test

#First test input
#Second test input
#Third test input

5#

Write a program allows a user to enter a word in an input field, translates that word into Pig Latin and prints this translation in the console. For the sake of modularity, we suggest that you build a helper function that handles all of the details of translating a word to Pig Latin (see the practice exercises for logic and conditionals ) . The provided template includes the operations for extracting the first letter and rest of the input word in the partial definition of this function. Pig Latin templatePig Latin solutionPig Latin (Checker)

# Convert input text into Pig Latin

###################################################
# Student should add code where relevant to the following.

try:
    import simplegui
except ImportError:
    import simplequi as simplegui


# Pig Latin helper function
def pig_latin(word):
    """Returns the (simplified) Pig Latin version of the word."""
    first_letter = word[0]
    rest_of_word = word[1:]

    # Student should complete function on the next lines.
    fl = first_letter

    if fl == 'a' or fl == 'e' or fl == 'i' or fl == 'o':
        return f'{word}way'
    else:
        return f'{rest_of_word}{fl}ay'


# Handler for input field
def get_input(inp):
    print(pig_latin(inp))


# Create frame and assign callbacks to event handlers
frame = simplegui.create_frame("Pig Latin translator", 200, 200)
frame.add_input('word to be piglatinized:', get_input, 100)


# Start the frame animation
frame.start()


###################################################
# Test

get_input("pig")
get_input("owl")
get_input("tree")

###################################################
# Expected output from test

#igpay
#owlway
#reetay

6#

Challenge: Add an interactive user interface for your implementation of “Rock-paper-scissors-lizard-Spock”. Create an input field that takes a player’s guess, generates a random computer guess, and prints out the player and computer choices as well as who won in the console. Make sure that your program checks for and correctly responds to bad input. RPSLS templateRPSLS solutionRPSLS (Checker)

# GUI-based version of RPSLS

###################################################
# Student should add code where relevant to the following.
try:
    import simplegui
except ImportError:
    import simplequi as simplegui


# Functions that compute RPSLS
def name_to_number(name):
    # convert name to number using if/elif/else
    # don't forget to return the result!
    if name == 'rock':
        return 0
    elif name == 'Spock':
        return 1
    elif name == 'paper':
        return 2
    elif name == 'lizard':
        return 3
    elif name == 'scissors':
        return 4
    else:
        print('Name not recognized')


def number_to_name(number):
    # convert number to a name using if/elif/else
    # don't forget to return the result!
    if number == 0:
        return 'rock'
    elif number == 1:
        return 'Spock'
    elif number == 2:
        return 'paper'
    elif number == 3:
        return 'lizard'
    elif number == 4:
        return 'scissors'
    else:
        print('Number not recognized')


def paper(player_choice):
    # print a blank line to separate consecutive games
    print()
    # print out the message for the player's choice
    print('Player chooses', player_choice)
    # convert the player's choice to player_number using the function
    # name_to_number()
    player_number = name_to_number(player_choice)

    # compute random guess for comp_number using random.randrange()
    import random
    comp_number = random.randrange(0, 5)

    # convert comp_number to comp_choice using the function number_to_name()
    comp_choice = number_to_name(comp_number)

    # print out the message for computer's choice
    print('Computer chooses', comp_choice)

    # compute difference of comp_number and player_number modulo five
    diff_comp_player = (comp_number - player_number) % 5

    # use if/elif/else to determine winner, print winner message
    if diff_comp_player == 0:
        print('Player and computer tie!')
    elif diff_comp_player <= 2:
        print('Computer wins!')
    else:
        print('Player wins!')


# Handler for input field
def get_guess(guess):
    if guess != 'rock' and \
       guess != 'lizard' and \
       guess != 'Spock' and \
       guess != 'scissors' and \
       guess != 'paper':
        print()
        print(f'Bad input "{guess}" to rpsls')
    else:
        paper(guess)


# Create frame and assign callbacks to event handlers
frame = simplegui.create_frame("GUI-based RPSLS", 200, 200)
frame.add_input("Enter guess for RPSLS", get_guess, 200)


# Start the frame animation
frame.start()


###################################################
# Test

get_guess("Spock")
get_guess("dynamite")
get_guess("paper")
get_guess("lazer")

###################################################
# Sample expected output from test
# Note that computer's choices may vary from this sample.

#Player chose Spock
#Computer chose paper
#Computer wins!
#
#Error: Bad input "dynamite" to rpsls
#
#Player chose paper
#Computer chose scissors
#Computer wins!
#
#Error: Bad input "lazer" to rpsls
#