Python 图形Tkinter Button

本文介绍了Tkinter中Button控件的基本用法及其多种样式设置方法。包括如何为Button绑定事件处理函数、调整按钮的外观样式如边框效果、设置按钮上的图像与文字布局等。此外还展示了如何设置按钮获得焦点及响应键盘事件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#coding=utf-8
'''第一个button 例子'''
#command:指定时间处理函数
from Tkinter import *
#定义Button的时间处理函数
def helloButton():
    print 'hello Button'

root = Tk()
#通过 command 属性来指定Button的事件处理函数
Button(root,
       text='点击一次控制台打印一句 hello Button',
       command=helloButton
       ).pack()
root.mainloop()


#coding=utf-8
'''Button 的外观效果'''

from Tkinter import *
root = Tk()
#flat, groove, raised, ridge, solid, or sunken
Button(root,
       text='hello button',
       relief=FLAT
       ).pack()
Button(root,
       text='hello button',
       relief=GROOVE
       ).pack()

Button(root,
       text='hello button',
       relief=RAISED
       ).pack()
Button(root,
       text='hello button',
       relief=SOLID
       ).pack()
Button(root,
       text='hello button',
       relief=SUNKEN
       ).pack()

#root.mainloop()

#图像居下,居上,居右,居左,文字位于图像之上
#root = Tk()
Button(root,
       text = 'botton',
       compound = 'bottom',
       bitmap = 'error'
       ).pack()
Button(root,
       text = 'top',
       compound = 'top',
       bitmap = 'error'
       ).pack()
Button(root,
       text = 'right',
       compound = 'right',
       bitmap = 'error'
       ).pack()
Button(root,
       text = 'left',
       compound = 'left',
       bitmap = 'error'
).pack()
Button(root,
       text = 'center',
       compound = 'center',
       bitmap = 'error'
       ).pack()

#root.mainloop()



'''Button 的焦点'''
# focus_set:设置当前组件得到焦点
#创建三个 Button,各自对应回调函数;
# 将第二个 Button 设置焦点,程序运行是按“Enter”,
#  判断程序的打印结果


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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值