Graphical User Interface with Python: Difference between revisions
No edit summary |
No edit summary |
||
Line 350: | Line 350: | ||
tk_time_utc.set(format(time_utc, '3.7f')) | tk_time_utc.set(format(time_utc, '3.7f')) | ||
root.after(2000, measure_temperature) | root.after(2000, measure_temperature) | ||
Here we see for the first time one of the bottlenecks of computing that runs a sequence of commands on a single ''thread''. Because it can only do one thing at a time, it cannot be taking data and displaying it and talking with the operator. To accomplish that you would need multiple threads or multiple processes and a way for these components to communicate with one another and stay in step, that is to synchronize with one another. One solution is to start separate processes that run asynchronously and let them communicate with a protocol you would design. This can be simple message passing through files or first-in-first-out buffers, or something more sophisticated that can manage multiple events with suitable responses. Another is to introduce threading, where the code maintains multiple synchronized paths of processing. Threading can be quite difficult to code however, and it is usually restricted to staying on one processor, so it does not take advantage of the many CPU's that are on modern hardware. | Here we see for the first time one of the bottlenecks of computing that runs a sequence of commands on a single ''thread''. Because it can only do one thing at a time, it cannot be taking data and displaying it and talking with the operator. To accomplish that you would need multiple threads or multiple processes and a way for these components to communicate with one another and stay in step, that is to synchronize with one another. One solution is to start separate processes that run asynchronously and let them communicate with a protocol you would design. This can be simple message passing through files or first-in-first-out buffers, or something more sophisticated that can manage multiple events with suitable responses. Another is to introduce threading, where the code maintains multiple synchronized paths of processing. Threading can be quite difficult to code however, and it is usually restricted to staying on one processor, so it does not take advantage of the many CPU's that are on modern hardware. | ||
We will encounter this issue again when we look at methods of incorporating responsive graphics and visualization into your programs, since those inevitably will use other modules that will take control of your program and disable the responsiveness of a tk interface. For now, we have solved it by letting the process that takes data alert tk to take another measurement later, effectively building an infinite loop within the tk.mainloop(). | We will encounter this issue again when we look at methods of incorporating responsive graphics and visualization into your programs, since those inevitably will use other modules that will take control of your program and disable the responsiveness of a tk interface. For now, we have solved it by letting the process that takes data alert tk to take another measurement later, effectively building an infinite loop within the tk.mainloop(). |
Revision as of 05:58, 4 April 2018
Python is inherently a programming language ideal for data analysis, and it works well by simply entering commands and seeing the results immediately, as we have seen in our short course on Python for Physics and Astronomy.For longer programs, or ones that are used frequently, the code is usually written into a file and then executed from the command line or as an element of a more complex set of scripted operations. However many users prefer a graphical user interface or "GUI" where mouse clicks, drop-down menus, check boxes, images, and plots access with the mouse and sometimes the keyboard. Python has that too, through a selection of tools that can be added to your code.
The most developed core component for this purpose is the Tk/Tcl library. In its most recent versions it provides a very direct way of running your programs within a GUI that is attractive, matches the native machine windows in appearance, and is highly responsive. While this is not the only one, it is a solid starting point and may be all you need. Later in this tutorial we will show you how to use Python running in background behind a graphical interface in a browser window which is another technique that is growing in capability as the browsers themselves gain computing power. However, the Tk library will allow you to build free-standing graphical applications that will run on all platforms on which Python runs.
A Tk Tutorial
An excellent starting point is the Tk documentation tutorial which will take you step by step through how to use this library in Python and in other languages. Work through this one first, and then return here and we will illustrated it with a few examples to show you how to use it in Physics and Astronomy applications.
Building a Program
In the tutorial you will see examples of code segments, and a few complete programs. Here, step by step, is how to make one that you can use as a template for something useful. First, you may see lines such as these at the beginning of a Tk program:
from tkinter import * from tkinter import ttk
which add the needed modules to your Python system. When you use "from xxx import *" that takes all the parts of xxx and adds them with their intrinsic names. Usually this is not an issue for such major parts of Python as tk, but it could cause a problem by overwriting or changing the meaning of something you are already using. Also, even if that is not the case, you cannot immediately tell if a function or constant is from tk, ttk or the core Python. An example would be Tk itself. The next lines of a simple program started this way may be
root = Tk() mainframe = ttk.Frame(root, padding=3 3 12 12")
and if we wanted to use a string inside the tkinter program we would have
mystring = StringVar()
somewhere in the code. The function "StringVar()" is not in the core Python. It comes from tkinter. Without the leading "from tkinter import *" the "StringVar()" is not defined.
For long term maintenance, a better approach is to load the module and give it a short name this way:
import tkinter as tk from tkinter import ttk
Now we have to use "tk" along with the component we are taking from tkinter, but the resulting code is much clearer. Let's complete a program that will convert feet to meters, following an example from the Tk website.
def calculate(*args): try: value = float(feet.get()) meters.set((0.3048 * value * 10000.0 + 0.5)/10000.0) except ValueError: pass root = tk.Tk() root.title("Feet to Meters")
mainframe = tk.ttk.Frame(root, padding="3 3 12 12") mainframe.grid(column=0, row=0, sticky=(tk.N, tk.W, tk.E, tk.S)) mainframe.columnconfigure(0, weight=1) mainframe.rowconfigure(0, weight=1)
feet = tk.StringVar() meters = tk.StringVar()
This way, all the tk-specific terms are clear. Notice the constants too, here "tk.W" for example, come from tkinter. Here's the remainder of the program that wil create a calculator window and run the conversion:
feet_entry = tk.ttk.Entry(mainframe, width=7, textvariable=feet) feet_entry.grid(column=2, row=1, sticky=(tk.W, tk.E)) tk.ttk.Label(mainframe, textvariable=meters).grid(column=2, row=2, sticky=(tk.W, tk.E)) tk.ttk.Button(mainframe, text="Calculate", command=calculate).grid(column=3, row=3, sticky=tk.W) tk.ttk.Label(mainframe, text="feet").grid(column=3, row=1, sticky=tk.W) tk.ttk.Label(mainframe, text="is equivalent to").grid(column=1, row=2, sticky=tk.E) tk.ttk.Label(mainframe, text="meters").grid(column=3, row=2, sticky=tk.W) for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5) feet_entry.focus() root.bind('<Return>', calculate)
root.mainloop()
The result will look like this when it runs:
The elements of the program are
- import tkinter
- define any functions such as "calculate" that you want to run
- create a graphical environment "root" window
- add a frame to the window
- put a grid inside the window frame
- add widgets for your interface located within the grid
- pad the widgets with space so they look good and Tk does the rest
- start the user interface
If you start the Python interpreter in a shell and perform the operations step by step up, as soon as the root object is created, a GUI window will appear on the screen. What comes after determines the properties of that display and its contents. For example, adding a title has a obvious effect to this window.
The window contains a frame which is called "mainframe" here, and when that is added the window shrinks to fit the frame. It is quite small because the frame does not contain anything but a few pixels of padding around its border. You can, at this point grab the edges of the tiny box and stretch it on your screen. The command
mainframe.grid(column=0, row=0, sticky=(tk.N, tk.W, tk.E, tk.S))
creates a grid that is anchored to tk points N, W, E, and S, that is to the corners. Within the grid we add components that will make our interface, and each component has properties we can set too. In this program we will have a frame that will enclose the our interface, and the window will resize automatically to enclose everything. The Tk grid handles the location of the "widgets" that are the elements your interface, and at least for many applications will make creating an nice-looking GUI simple.
First, we add the frame:
mainframe.columnconfigure(0, weight=1) mainframe.rowconfigure(0, weight=1)
Then we define the strings that will hold input and the output from the box that will accept the input:
feet = tk.StringVar() feet_entry = tk.ttk.Entry(mainframe, width=7, textvariable=feet)
The object called "feet_entry" represents this box on the screen. The box is located inside the GUI by the grid that is defined in mainframe
feet_entry.grid(column=2, row=1, sticky=(tk.W, tk.E))
and we put it in column 2 and row 1. As soon as this is issued, a box appears in the GUI and is centered because there is nothing more there. The result of the calculation will be a string that we will show on the interface as a label below the input in the second row
meters = tk.StringVar() tk.ttk.Label(mainframe, textvariable=meters).grid(column=2, row=2, sticky=(tk.W, tk.E))
Notice how the string is given as a variable without quotes, so the interface will update when this variable changes. Along with this, we include fixed labels for the input units, an explanation and the output units:
tk.ttk.Label(mainframe, text="feet").grid(column=3, row=1, sticky=tk.W) tk.ttk.Label(mainframe, text="is equivalent to").grid(column=1, row=2, sticky=tk.E) tk.ttk.Label(mainframe, text="meters").grid(column=3, row=2, sticky=tk.W)
Lastly, we add a button that will start the calculation
tk.ttk.Button(mainframe, text="Calculate", command=calculate).grid(column=3, row=3, sticky=tk.W)
All of these elements are children of the frame, and to have them appear on the grid with a little padding we take each one and configure the grid for it
for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5)
Now focus the window on the entry box to make it easy on the user and use the Return key to start a conversion (as well as the button)
feet_entry.focus() root.bind('<Return>', calculate)
The GUI is ready to use. Start it with this
root.mainloop()
You will find this program among our examples as the file "feet_to_meters_tk_explicit.example".
Interfacing an Instrument: Phidgets
The power of a graphical user interface or GUI is that it is easy to use when the actions are repetitive and the end user does not need to know the details of what is happening. It will deliver to the user the result that is needed and even provide cues on how to make that happen. As in the calculation of a feet to meters conversion, the GUI does not inform the user of how it is done, and simply does it without a fuss. In a laboratory environment that can be very useful, assuming the user understands the process, and needs the answer on a single click. An example would be if there is an instrument which is capable of making a measurement and the user needs to know the result.
The Canadian Company Phidgets manufactures a wide variety of small modules for the hobbiest, lab, and even industry that provide control of motors, relays digital signal levels, analog to digital (ADC) and digital to analog (DAC) conversion, and environmental sensors for temperature, humidty, pressure, light level, and stress. Their hardware has been traditionally designed to interface with computers using the USB bus, and recently (2017) they introduced a simpler 2-wire interface that is more versatile for some applications. They also make single board computers to run their devices under Linux. Their products are not unlike the famous Rasberry Pi or Beagle Board systems, except they are uniformly supported, consistently manufactured, and offered with supporting opensource software. Conceptually it offers an Internet of Things for the lab. Of course there are many other vendors with similar intent, National Instruments with their proprietary and mostly Windows-only LabVIEW software, Labjack with cost effective versatile interfaces and solid cross-platform Python support, and Measurement Computing with cutting edge interfaces supported in Linux and Python worthy of consideration. Whatever you pick for your lab experiments, if it has a Python library or module, you will have access to the device from within the Python program. Therefore, it may be useful to have an example of what can be done to interface a user with a device through a Tk GUI.
The instrument we will use is an infrared thermometer from Phidgets because it uses interesting basic physics, and it is so easily interfaced the device technology does not intrude on showing the programming elements. The device is very small, and is powered from the USB interface. It consists of an infrared sensing pyrometer that is internally a Peltier array of thermocouples, and the electronics to connect it to the computer through the standard bus. The black anodized aluminum cylinder is baffled such that infrared light from a spot 10 degrees in diameter (1 meter at a distance of 11.4 meters) illuminates the sensor. The electronics make a measurement of the IR radiation by determining the voltage from the Peltier array, which is to say the temperature it reaches in equilibrium with the incident radiation. It also measures the ambient temperature. The signal it gets is fundamentally the blackbody temperature of the 10 degree spot, and the device functions as a non-contact thermometer that can measure from -70 to +380 celsius with a temperature resolution of 0.02 C and an error of 4 C.
The program which uses this device is similar to the one for doing a conversion calculation, but it takes its data from the instrument instead, beginning this way --
#!/usr/bin/python3
# Phidgets IR temperature sensor example program # Driven by IR sensor change # Added utc logging
import sys import time from time import gmtime, strftime # for utc from time import sleep # for delays from Phidget22.Devices.TemperatureSensor import * from Phidget22.PhidgetException import * from Phidget22.Phidget import * from Phidget22.Net import * import tkinter as tk from tkinter import ttk
# # Initial parameters #
global site_longitude global diagnostics global time_utc global temperature_celsius global polling_flag
You'll notice there are modules loaded from the Phidget22 package that the company supplies. These modules have an application programming interface (an "API") that we can use to control are get information from the sensor. The other new items are declarations that some variables are global, meaning that they will be used in other subroutines. The full program is on the examples page tk_temperature.example.
The graphical interface is built as before
# Create the root window root = tk.Tk() root.title("IR Temperature Sensor")
# Add a frame to the window
mainframe = tk.ttk.Frame(root, padding="3 3 12 12") mainframe.grid(column=0, row=0, sticky=(tk.N, tk.W, tk.E, tk.S)) mainframe.columnconfigure(0, weight=1) mainframe.rowconfigure(0, weight=1)
# Create Tk strings for displayed information
tk_temperature_celsius = tk.StringVar() tk_time_utc = tk.StringVar() tk_temperature_celsius.set('100.') tk_time_utc.set('0.')
#Add widgets to the grid within the frame
tk.ttk.Label(mainframe, text="IR Sensor").grid(column=2, row=1, sticky=tk.W) tk.ttk.Label(mainframe, text="Time").grid(column=1, row=2, sticky=tk.W) tk.ttk.Label(mainframe, textvariable=tk_time_utc).grid(column=2, row=2, sticky=(tk.W, tk.E)) tk.ttk.Label(mainframe, text="hours (UTC)").grid(column=3, row=2, sticky=tk.W)
tk.ttk.Label(mainframe, text="Temperature").grid(column=1, row=3, sticky=tk.W) tk.ttk.Label(mainframe, textvariable=tk_temperature_celsius).grid(column=2, row=3, sticky=(tk.W, tk.E)) tk.ttk.Label(mainframe, text="Celsius").grid(column=3, row=3, sticky=tk.E)
tk.ttk.Button(mainframe, text="Start", command=start_irsensor).grid(column=2, row=4, sticky=tk.W) tk.ttk.Button(mainframe, text="Stop", command=stop_irsensor).grid(column=2, row=5, sticky=tk.W) tk.ttk.Button(mainframe, text="Exit", command=exit_irsensor).grid(column=2, row=6, sticky=tk.W)
# Pad the widgets for appearance
for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5)
The sensor is connected to the code as soon as the GUI is built with this
- Open a connection to the sensor and assign a channel
try: ch = TemperatureSensor() except RuntimeError as e: print("Runtime Exception %s" % e.details) print("Press Enter to Exit...\n") readin = sys.stdin.read(1) exit(1)
which attempts to connect to and if that fails exits with an error message. Once connected, it tells the instrument code how to respond to events
ch.setOnAttachHandler(TemperatureSensorAttached) ch.setOnDetachHandler(TemperatureSensorDetached) ch.setOnErrorHandler(ErrorEvent) ch.setOnTemperatureChangeHandler(TemperatureChangeHandler)
which are self-explanatory functions that do something when the event occurs. The important one for our use is
def TemperatureChangeHandler(self, temperature): global temperature_celsius global time_utc global polling_flag temperature_celsius = temperature time_utc = utcnow() if polling_flag: tk_temperature_celsius.set(format(temperature_celsius, '3.2f')) tk_time_utc.set(format(time_utc, '3.7f'))
Here the global variables are used to communicate with the handler. They take the temperature that is identified as having changed and save it so we can use it in other places, they note the time of the measurement, and they set two tk string variables that will display the temperature and the time. The polling_flag is used as an on/off switch on the user interface. It is changed on response to a button press to start or stop the sensor readings. Alternatively we could poll the sensor ourselves, either by a button press or by a timer of some sort, but this method lets the intrument interface tell us when it has a new value.
# Define the button press actions
def start_irsensor(): global temperature_celsius global time_utc global polling_flag polling_flag = True tk_temperature_celsius.set(format(temperature_celsius, '3.2f')) tk_time_utc.set(format(time_utc, '3.7f')) return()
def stop_irsensor(): global temperature_celsius global time_utc global polling_flag polling_flag = False tk_temperature_celsius.set(format(temperature_celsius, '3.2f')) tk_time_utc.set(format(time_utc, '3.7f')) return()
def exit_irsensor(): try: ch.close() except PhidgetException as e: print("Phidget Exception %i: %s" % (e.code, e.details)) if diagnostics: print("Press Enter to Exit...\n") readin = sys.stdin.read(1) exit(1)
print("Closed TemperatureSensor device") exit(0) return()
We then start the GUI and let it update the temperature while giving us control to start and stop the updates, or exit the program with a button press.
# # Polling loop within GUI #
if diagnostics: print("Gathering data ...")
# Temperature change handler will provide new data
# Tk standard is to use this blocking method root.mainloop()
exit()
The running program looks like this:
Events and Control Within the User Interface
When a tkinter program has created the interface the last step is to make it responsive to the user. In these examples you'll see this function call
root.mainloop()
without an argument. That turns over control to the tkinter system that will idle waiting for an event for which it has been told to respond. An example is a button press, as above, which was programmed with a line such as this one
tk.ttk.Button(mainframe, text="Exit", command=exit_irsensor).grid(column=2, row=6, sticky=tk.W)
that created a button to exit the program. When this button is depressed or clicked, the routine "exit_irsensor()" is run. In this example that routine disconnects the program from the sensor and cleanly closes up. Other buttons in our program set flags and variables that determine how the program operates. Notice that the events are all generated within tk. Our external event is a change in the value of the temperature that is measured. That change is sensed by a different process that is running asynchronously and not directly in communication with tk. We have made them work together by having the separate process -- the handler for a change in temperature value -- set the string that displays this temperature. Whenever that string is set, an event is created that tk notices, and it updates the display.
Tkinter programs are designed to use the root.mainloop() function to keep the display responsive to the user. However root.mainloop() is "blocking" any other operations. If, for example, we wanted to poll the device from within our program we could not do that because the program is in an infinite loop looking for user input to the interface. There is, however, a simple solution. Instead of starting root.mainloop() and letting it run, we tell it to also run another routine after it has started. It is done this way:
root.after(2000, measure_temperature) root.mainloop()
The after method takes arguments that are the delay time in milliseconds and the name of the function. The mainloop starts a timer and 2000 milliseconds later it runs measure_temperature()
def measure_temperature(): if polling_flag: tk_temperature_celsius.set(format(temperature_celsius, '3.2f')) tk_time_utc.set(format(time_utc, '3.7f')) # Reschedule event in 2 seconds root.after(2000, measure_temperature)
which upates the temperature on the display if polling_flag is true. It also tells mainloop to schedule another run of measure_temperature after 2000 more milliseconds, and so on.
We have simply modified the previous example where the temperature measurement is done in another process set up by the Phidgets22 library and left the values of temperature and time in global variables for us to use later. More commonly, we could have made the measure here instead by calling that method on the open channel of the device:
def measure_temperature(): global temperature_celsius global time_utc global polling_flag global ch if polling_flag: temperature_celsius = ch.getTemperature() time_utc = utcnow() tk_temperature_celsius.set(format(temperature_celsius, '3.2f')) tk_time_utc.set(format(time_utc, '3.7f')) root.after(2000, measure_temperature)
Here we see for the first time one of the bottlenecks of computing that runs a sequence of commands on a single thread. Because it can only do one thing at a time, it cannot be taking data and displaying it and talking with the operator. To accomplish that you would need multiple threads or multiple processes and a way for these components to communicate with one another and stay in step, that is to synchronize with one another. One solution is to start separate processes that run asynchronously and let them communicate with a protocol you would design. This can be simple message passing through files or first-in-first-out buffers, or something more sophisticated that can manage multiple events with suitable responses. Another is to introduce threading, where the code maintains multiple synchronized paths of processing. Threading can be quite difficult to code however, and it is usually restricted to staying on one processor, so it does not take advantage of the many CPU's that are on modern hardware.
We will encounter this issue again when we look at methods of incorporating responsive graphics and visualization into your programs, since those inevitably will use other modules that will take control of your program and disable the responsiveness of a tk interface. For now, we have solved it by letting the process that takes data alert tk to take another measurement later, effectively building an infinite loop within the tk.mainloop().