Python Programming/User Interaction

From Wikibooks, open books for an open world
< Python Programming
Jump to: navigation, search

There are two ways to retrieve user input: the first is using the console window (Command Line Interface) and the second is using the Graphical User Interface (GUI).

Contents


[edit] Console Windows (Command Line Interface)

Python's built-in function to retrieve users input on a console is input(). It accepts a string argument which is displayed on the terminal before accepting the user input.

Note:
These examples are Python 3 specific. In Python 2, there were input() and raw_input() functions. Python 2's equivalent to Python 3's input() was raw_input()! Python 2's input() function was equivalent to Python 3's eval(input()) combination, either of which can be a security risk in some cases and should be reserved for system administrators writing scripts for trusted users.

# Ask user for his name and stores
name = input("Please enter your name: ")
# Display the name entered by the user.
print("Hello", name)

If the information entered by the user needs to be numeric to perform some calculation the return value must be converted using the float() or int() conversion function.

# Retrieve user age and flatter him/her
age = int(input("Please enter your age: "))
if   age > 30:
    print("You're already", age, "years old? You don't look a day over", age - age // 10)
elif age < 20:
    print("You're only", age, "years old? You could easily pass for a", age + 2, "year old")
else:
    print("You're", age, "years old")

As you may expect coding all the input for a big application and all the validation will increase the file size. To make steps simpler we can create an object (using a Class) that handles retrieving the data and validating.

class AInput:  # We can't use input as it is a existent function name, so we use AInput for Advance Input
   ''' This class will create a object with a simpler coding interface to retrieve console input'''
   def __init__(self, msg=""):
      ''' This will create a instance of ainput object'''
      self.data = ""  # Initialize a empty data variable
      if not msg == "":
         self.ask(msg)
 
   def ask(self, msg, req=0):
      ''' This will display the prompt and retrieve the user input.'''
      if req == 0:
         self.data = input(msg)  # Save the user input to a local object variable
      else:
         self.data = input(msg + " (Require)")
 
      # Verify that the information was entered and its not empty. This will accept a space character. Better Validation needed
      if req == 1 and self.data == "":
         self.ask(msg, req)
 
   def getString(self):
      ''' Returns the user input as String'''
      return self.data
 
   def getInteger(self):
      ''' Returns the user input as a Integer'''
      return int(self.data)
 
   def getNumber(self):
      ''' Returns the user input as a Float number'''
      return float(self.data)

Note:
Notice we only validate if the prompt is required and it is not empty. Also notice that if a prompt is required and the user just hit <ENTER> it can fall in a infinite loop. You probably need a more advanced validation and error verification method, but it's up to you.

With this tool at our disposal displaying, retrieving and validating user input is a breeze. The use of the code will run like this. For this example we are using a single line to display the call and retrieve the information.

name = AInput("Please enter your first name: ").getString()
age = AInput("Now enter your age: ").getInteger()
wage = AInput("And your hourly wage: ").getNumber()
print(name, age, wage)

To test this code copy the following to a python script file (e.g. userInteraction.py)

class AInput:  # We can't use input as it is a existent function name, so we use AInput for Advance Input
   ''' This class will create a object with a simpler coding interface to retrieve console input'''
   def __init__(self, msg=""):
      ''' This will create a instance of ainput object'''
      self.data = ""  # Initialize a empty data variable
      if not msg == "":
         self.ask(msg)
 
   def ask(self, msg, req=0):
      ''' This will display the prompt and retrieve the user input.'''
      if req == 0:
         self.data = input(msg)  # Save the user input to a local object variable
      else:
         self.data = input(msg + " (Require)")
 
      # Verify that the information was entered and its not empty. This will accept a space character. Better Validation needed
      if req == 1 and self.data == "":
         self.ask(msg, req)
 
   def getString(self):
      ''' Returns the user input as String'''
      return self.data
 
   def getInteger(self):
      ''' Returns the user input as a Integer'''
      return int(self.data)
 
   def getNumber(self):
      ''' Returns the user input as a Float number'''
      return float(self.data)
 
def main():
        name = AInput("Please enter your first name: ").getString()
        age = AInput("Now enter your age: ").getInteger()
        wage = AInput("And your hourly wage: ").getNumber()
        print(name, age, wage)
 
if __name__ == '__main__':
        main()

[edit] Graphical User Interface (GUI)

Python has many different GUI toolkits, of which the most standard is Tkinter which comes with Python. This section will be limited to basic Tkinter programming fundamentals, a more detailed reference can be found in GUI Programming Modules of this wikibook.

Lets proceed by creating a classic developer Hello World example with the following code.

import tkinter
 
# Define input retrieve function for application input
def retrieve_text():
    print(app_entry.get())
 
if __name__ == "__main__":
 
    # Create window (or form)
    app_win = tkinter.Tk()
 
    # Create label
    app_label = tkinter.Label(app_win, text="Enter value")
    app_label.pack()
 
    # Create entry box
    app_entry = tkinter.Entry(app_win)
    app_entry.pack()
 
    # Create button
    app_button = tkinter.Button(app_win, text="Print Value", command=retrieve_text)
    app_button.pack()
 
    # Initialize GUI loop
    app_win.mainloop()

On the first line we actually import the Tkinter library in use by using import tkinter. Next a function is created to retrieve the value from the input object use in the GUI. For the moment the value will be print to the console.

Next we create a window where all the GUI components (or widgets as the Tkinter toolkit calls them) are placed. We do this via a call to Tk(). Think of it like a painting canvas where we draw our application interface.

Having define the window we proceed to create a label widget. Notice the first argument in the Label() call is the variable holding the window (this is for binding purposes) and the next argument is the label's text. The next line binds the label to the window by using the pack() method.

Note:
The Tkinter toolkit has two layout system: pack and grid, Pack is the simpler to use while Grid provides a table-like layout. Only one layout can be in use for Window or Frame.

Next step is the entry box widget. Tkinter provides the Entry object (known as a Textbox in other programming languages). Notice that again we need the window object as first argument. The next lines bind the entry object with the window.

Next is the creation of the button widget for the application. Like for the other calls the window object is the first argument. The button text value is filled much like we did with the label and the button's action is filled using the command argument. Notice that the command argument doesn't have quotes as it is not a string but is a reference to the function first defined. The next line proceeds to bind the button to the window.

On the last line a call to app_win.mainloop() allows the Tkinter application to run.

[edit] Advanced OOP GUI

So far it seems tedious to create a GUI using Python, especially with so much code to write for such a simple program. But when you bring OOP concepts into the mix it is different. For a moment think of an application that requires a couple of inputs with labels to identify them. The OOP methodology has the advantage of letting us create a new object that presents the label and entry widget at the same time, is reusable, and can be called with one line of code.

The code below does just that, it wraps a label and entry widget inside a Tkinter Frame. The object requires the parent window as first argument and the label text as the second, while the text function returns a string value for the user input. A more advanced text box can include validation and data retrieval.

# Eliminate the need to prefix everything with "tkinter."
from tkinter import *
 
# Define our Textbox 
class Textbox(Frame):
 
    def __init__(self, parent, msg):
        # Initialize the Frame properties by explicitly calling its init method
        Frame.__init__(self, parent)
 
        # Create the Textbox Label on the left side
        self.g_label = Label(self, text=msg)
        self.g_label.pack(side=LEFT, expand=False)
 
        # Create the Textbox Entry on the right side
        self.g_entry = Entry(self)
        self.g_entry.pack(side=LEFT, fill=X, expand=True)
 
        # Proceed to pack the frame
        self.pack(fill=X, anchor=NW, expand=True)
 
    def text(self):
        # Textbox text value retrieval
        return self.g_entry.get()

Now on our multi-input application we can use this new object with one simple line for each instance:

name = Textbox(win, "Name:")

Notice that we don't need to call the pack method as the text box object packs itself on the last line of the __init__. This is not practical on complex layout application since the object controls this function, but works wonders for small script GUI.

Personal tools
Namespaces
Variants
Actions
Navigation
Community
Toolbox
Sister projects
Print/export