Advertisement
here2share

# TkMessageBox.py

Apr 10th, 2015
356
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.91 KB | None | 0 0
  1. # TkMessageBox.py -- Tkinter GUI Component Interaction
  2.  
  3. import random
  4. from Tkinter import *
  5. import tkMessageBox
  6.  
  7.  
  8. class Application(Frame):
  9.     def __init__(self, master):
  10.         Frame.__init__(self, master)
  11.         self.counter = 0
  12.         self.contents = StringVar()
  13.         self.contents.set(str(self.counter))
  14.         self.pack(expand=True, fill='both', padx=10, pady=15)
  15.         self.create_widgets()
  16.  
  17.     def increment(self, *args):
  18.         self.counter += 1
  19.         self.update_entry()
  20.  
  21.     def random(self):
  22.         if tkMessageBox.askyesno("Confirmation", "Reset to random value ?"):
  23.             self.counter = random.randint(0, 5000)
  24.             self.update_entry()
  25.         else:
  26.             self.counter = 0
  27.             self.update_entry()
  28.  
  29.     def entry_updated(self, event, *args):
  30.         if not event.char:
  31.             return 'break'
  32.         if not event.char.isdigit():
  33.             tkMessageBox.showerror('Error', 'Invalid input !')
  34.             return 'break'
  35.         self.counter = int('%s%s' % (self.contents.get(), event.char))
  36.  
  37.     def update_entry(self):
  38.         self.contents.set(str(self.counter))
  39.         self.entry['textvariable'] = self.contents
  40.  
  41.     def create_widgets(self):
  42.         options = {'expand': True, 'fill': 'x', 'side': 'left', 'padx': 5}
  43.         self.entry = Entry(self)
  44.         self.entry.bind('<Key>', self.entry_updated)
  45.         self.entry.pack(**options)
  46.         self.update_entry()
  47.         self.increment_button = Button(self, text='Increment', command=self.increment)
  48.         self.increment_button.pack(**options)
  49.         self.random_button = Button(self, text='Random', command=self.random)
  50.         self.random_button.pack(**options)
  51.  
  52.  
  53. if __name__ == '__main__':
  54.     root = Tk()
  55.     try:
  56.         app = Application(master=root)
  57.         app.master.title("Sample Code")
  58.         app.mainloop()
  59.     except KeyboardInterrupt:
  60.         root.destroy()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement