GUI
Peter Otten
__peter__ at web.de
Sat Jan 28 08:58:54 EST 2017
hany.amin.mishriky at gmail.com wrote:
> hay , i am new in the coding world,i would like to understand how a python
> program is communicating with GUI, for example, if i have a code that
> require the user to enter a value ,then this code will do some
> calculations and return a value to the user, how to do that?
A command line script adding two numbers will look like this:
x = input_int("Enter x:")
y = input_int("Enter y:")
print("x + y =", x + y)
This script will not continue to ask for y until the user has entered the
value for x
In a GUI you have to provide widgets that allow the user to interact with
the GUI . Let's assume make_widget() creates an entry widget and shows it in
a window. Then we can create the part of the GUI where the user enters the x
and y value with:
entry_x = make_widget()
entry_y = make_widget()
Now we need one more widget to show the result:
entry_sum = make_widget()
We also need a function that recalculates the contents of entry_sum whenever
the user changes x or y:
def recalculate_sum():
x = int(entry_x.get_value())
y = int(entry_y.get_value())
entry_sum.set_value(sigma)
But when should this function run? We have to connect it to the widgets on
whose changes it should react. Such a function is called "callback":
# assume that every time the contents of entry_x/y change it calls
# self.on_change()
entry_x.on_change = recalculate_sum
entry_y.on_change = recalculate_sum
Finally you enter an infinite loop that waits for and handles GUI events,
the most interesting being user activities like typing a digit into one of
your widgets.
run_event_loop()
There a many GUIs, but they all tend to work in a way similar to the one
sketched above. Here's a translation of the above pseudo-code to tkinter:
import tkinter as tk
def make_entry(caption, row):
"""Create a Label and an Entry.
Return the StringVar associated with the Entry.
"""
# the text displayed to the left of the Entry
label = tk.Label(root, text=caption)
label.grid(row=row, column=0)
var = tk.StringVar() # holds the text entered into the Entry
entry = tk.Entry(root, textvariable=var)
entry.grid(row=row, column=1, sticky=tk.EW)
return var
def calculate_sum(*args):
"""Callback invoked on changes of x or y
The GUI passes some arguments (*args) that we are not interested in.
"""
try:
x = int(var_x.get())
y = int(var_y.get())
sigma = x + y
except ValueError as err:
# if x or y aren't valid integers
# show an error message instead of the sum
sigma = err
var_sum.set(sigma)
# Create the main window
root = tk.Tk()
# Have the second column take all extra space
root.columnconfigure(1, weight=1)
var_x = make_entry("x", 0)
var_y = make_entry("y", 1)
var_sum = make_entry("x + y =", 2)
# Tell the GUI to invoke calculate_sum() after every change of x or y
var_x.trace("w", calculate_sum)
var_y.trace("w", calculate_sum)
root.mainloop()
More information about the Python-list
mailing list