现在的位置: 首页 > 综合 > 正文

Tkinter:Button(1)

2013年05月03日 ⁄ 综合 ⁄ 共 2177字 ⁄ 字号 评论关闭

一个简单的Button例子:

from Tkinter import *
def helloButton():
      print 'Hello Button !'
root=Tk()
button=Button(root,text='pres me',command=helloButton) #当按button时将调用helloButton函数。
button.pack()
root.mainloop()

command:指定事件处理函数

效果:

            

Button的外观效果:

from Tkinter import *
root=Tk()
Button(root,text = 'press me',relief=FLAT).pack()
Button(root,text = 'press me',relief=GROOVE).pack()
Button(root,text = 'press me',relief=RAISED).pack()
Button(root,text = 'press me',relief=RIDGE).pack()
Button(root,text = 'press me',relief=SOLID).pack()
Button(root,text = 'press me',relief=SUNKEN).pack()
root.mainloop()

relief:设置Button 的外观效果,可选的值有:flat, groove, raised, ridge, solid, or sunken。

效果:

Button显示图像效果:

from Tkinter import *
root=Tk()
img=PhotoImage(file='001.gif')
Button(root,image=img,text = 'press me',relief=RAISED).pack()
Button(root,text = 'press me',relief=RIDGE).pack()
root.mainloop()

image图像的加载方法img = PhotoImage(file = filepath)

bimap位图的加载方法bp = PhotoImage(file = filepath),bitmap:使用X11 格式的bitmap,文件后缀:.xbm。

效果:

Button显示位图与文本:

from Tkinter import *
root=Tk()
Button(root,text='press me',compound='top',bitmap='error').pack()
Button(root,text='press me',compound='bottom',bitmap='question').pack()
Button(root,text='press me',compound='left',bitmap='warning').pack()
Button(root,text='press me',compound='right',bitmap='hourglass').pack()
Button(root,text='press me',compound='center',bitmap='info').pack()
root.mainloop()

compound:指定文本与图像位置关系
bitmap:指定位图

效果:

Button的焦点:

from Tkinter import *
def cb1():
      print 'button1 clicked'
def cb2(event):
      print 'button2 clicked'
def cb3():
      print 'button3 clicked'

root=Tk()
b1 = Button(root,text = 'Button1',command = cb1)
b2 = Button(root,text = 'Button2')
b2.bind("<Return>",cb2)
b3 = Button(root,text = 'Button3',command = cb3)
b1.pack()
b2.pack()
b3.pack()
b2.focus_set()
root.mainloop()

上例中使用了bind 方法,它建立事件与事件处理函数(响应函数)之间的关系,每当产生<Return>事件后,程序便自动的调用cb2,与cb1,cb3 不同的是,它本身还带有一个参数----event,这个参数传递响应事件的信息。第二个button被设置焦点,当按Enter键,将调用它的事件处理函数。

效果:

显示focus的详细信息:

from Tkinter import *
def printEventInfo(event):
      print 'event.time = ' , event.time
      print 'event.type = ' , event.type
      print 'event.WidgetId = ', event.widget
      print 'event.KeySymbol = ',event.keysym

     
root = Tk()
b = Button(root,text = 'Infomation')
b.bind("<Return>",printEventInfo)
b.pack()
b.focus_set()
root.mainloop()

效果:

抱歉!评论已关闭.