[Tutor] help with Tkinter, please
Michael Lange
klappnase at freenet.de
Thu Nov 23 17:01:35 CET 2006
On Thu, 23 Nov 2006 02:07:17 -0800
Dick Moores <rdm at rcblue.com> wrote:
> I think I see how to make a simple GUI with Tkinter, but I still
> don't see how to use one with even a simple, previously non-GUI
> Python script. I'm wondering if someone could create an example for
> me, using the 2 functions fact() and printFact() at
> <http://www.rcblue.com/Python/fact.txt>. I'm thinking of something
> really plain and simple. A frame widget, an entry widget, and a text
> widget. The user enters an integer n (which can be very large), and
> the text widget shows n! in 2 formats, as the output of a modified
> printFact(). Maybe a button is also necessary?
>
Hi Dick,
assuming the functions you want to use are in a separate module "fact.py",
a simple (and dirty) solution might look like
from Tkinter import *
import fact
root = Tk()
entry = Entry(root)
entry.pack(side='top')
text = Text(root)
text.pack(side='top')
# now you need a callback that calls fact() and inserts the result into the text widget
def compute_fact():
value = int(entry_get())
result = fact.fact(value)
newtext = 'Result: %d\n' % result# change this to the output format you wish
text.insert('end', result)
button = Button(root, text="Compute fact", command=compute_fact)
button.pack(side='top')
root.mainloop()
In case you do not want an extra button, you can bind the compute_fact() callback
to Key-Return events for the entry:
entry.bind('<Return>', compute_fact)
however you will have to change the callback's constructor to accept an event object
as argument:
def compute_fact(event):
(...)
or :
def compute_fact(event=None):
(...)
which allows both.
In case you want the output formatting done in the fact module, change the printFact() function,
so that it *returns* a string instead of printing it to stdout, so you can use a callback like:
def compute_fact(event=None):
text.insert('end', fact.printFact(int(entry.get())))
I hope this helps
Michael
More information about the Tutor
mailing list