Friday, July 3, 2015

Python: Tkinter GUI (4)


Abstract: press a button and activate a message window





# -*- coding: utf-8 -*-
"""
Created on Thu Jul 2 12:35:28 2015

@author: yuan
"""

import sys
from Tkinter import *
makemodal=(len(sys.argv)>1)

class MyWindow:
def __init__(self, title='tkinter'):
self.win=Tk()
self.win.title(title)
self.title=title
#add a label
def win_label(self, txt):
widget=Label(self.win, text=txt)
widget.config(bg='green', fg='black')
widget.config(font=('times', 20, 'normal') )
widget.config(height=5, width=25)
widget.pack(expand='yes', fill='both')
return self.win
#add a button configuration
def config_button(self, widget, txt):
widget.config(text=txt)
widget.config(cursor='gumby')
widget.config(bd=5, relief='raised')
widget.config(bg='cyan', fg='black')
widget.config(font=('helvetica', 20, 'bold') )
widget.pack(padx=10, pady=10)
widget.pack(side='left', expand='yes')
return widget
#add a button
def exec_button(self, label, func):
widget=Button(self.win, command=func )
widget=self.config_button(widget, label)
return self.win
#message box
def dialog(self):
win = Tk()
win.title('Message') # make a new window
Label(win, text='Format hard drive').pack() # add a few widgets
Button(win, text='OK', command=win.destroy).pack() # set destroy callback
if makemodal:
win.focus_set() # take over input focus,
win.grab_set() # disable other windows while I'm open,
win.wait_window() # and wait here until win destroyed

###main program

#the simplest label window
ww=MyWindow(title='Tkinter')

#the window will be present on the left top corner of the screen
#win=ww.win_v1('Hello GUI world')

#some decorations of labels and titles
win=ww.win_label('Hello world!')
win=ww.win_label('Good luck!')


#add two buttons
win=ww.exec_button('message', ww.dialog )
win=ww.exec_button('quit', sys.exit )


win.mainloop()

No comments:

Post a Comment