/Demo/tkinter/matt/entry-with-shared-variable.py

http://unladen-swallow.googlecode.com/ · Python · 46 lines · 23 code · 9 blank · 14 comment · 0 complexity · e3cc599b5e9f142d05f2978d50561bbc MD5 · raw file

  1. from Tkinter import *
  2. import string
  3. # This program shows how to make a typein box shadow a program variable.
  4. class App(Frame):
  5. def __init__(self, master=None):
  6. Frame.__init__(self, master)
  7. self.pack()
  8. self.entrythingy = Entry(self)
  9. self.entrythingy.pack()
  10. self.button = Button(self, text="Uppercase The Entry",
  11. command=self.upper)
  12. self.button.pack()
  13. # here we have the text in the entry widget tied to a variable.
  14. # changes in the variable are echoed in the widget and vice versa.
  15. # Very handy.
  16. # there are other Variable types. See Tkinter.py for all
  17. # the other variable types that can be shadowed
  18. self.contents = StringVar()
  19. self.contents.set("this is a variable")
  20. self.entrythingy.config(textvariable=self.contents)
  21. # and here we get a callback when the user hits return. we could
  22. # make the key that triggers the callback anything we wanted to.
  23. # other typical options might be <Key-Tab> or <Key> (for anything)
  24. self.entrythingy.bind('<Key-Return>', self.print_contents)
  25. def upper(self):
  26. # notice here, we don't actually refer to the entry box.
  27. # we just operate on the string variable and we
  28. # because it's being looked at by the entry widget, changing
  29. # the variable changes the entry widget display automatically.
  30. # the strange get/set operators are clunky, true...
  31. str = string.upper(self.contents.get())
  32. self.contents.set(str)
  33. def print_contents(self, event):
  34. print "hi. contents of entry is now ---->", self.contents.get()
  35. root = App()
  36. root.master.title("Foo")
  37. root.mainloop()