您的位置:首页 > 编程语言 > Python开发

python Tkinter之Button

2016-09-12 15:50 288 查看
Button小部件是一个标准的Tkinter的部件,用于实现各种按钮。按钮可以包含文本或图像,您可以调用Python函数或方法用于每个按钮。 Tkinter的按钮被按下时,会自动调用该函数或方法。

该按钮可以只显示在一个单一的字体的文本,但文本可能跨越一个以上的行。此外,一个字符可以有下划线,例如标记的键盘快捷键。默认情况下,使用Tab键可以移动到一个按钮部件。

通常使用工具栏按钮,在应用程序窗口,并接受或解雇在对话框中输入的数据。


Button按钮属性

函数
描述
text
显示文本内容
command
指定Button的事件处理函数
compound
指定文本与图像的位置关系
bitmap
指定位图
focus_set
设置当前组件得到的焦点
master
代表了父窗口
bg
设置背景颜色
fg
设置前景颜色
font
设置字体大小
height
设置显示高度、如果未设置此项,其大小以适应内容标签
relief
指定外观装饰边界附近的标签,默认是平的,可以设置的参数;

flat、groove、raised、ridge、solid、sunken
width
设置显示宽度,如果未设置此项,其大小以适应内容标签
wraplength
将此选项设置为所需的数量限制每行的字符,数默认为0
state
设置组件状态;正常(normal),激活(active),禁用(disabled)
anchor
设置Button文本在控件上的显示位置

可用值:n(north),s(south),w(west),e(east),和ne,nw,se,sw
bd
设置Button的边框大小;bd(bordwidth)缺省为1或2个像素
textvariable
设置Button与textvariable属性


Button按钮方法

以下是Button常用的小工具

方法
描述
flash()
Flash the button. This method redraws the button several times, alternating between active and normal appearance.
invoke()
Invoke the command associated with the button.


Python Tkinter Button示例代码

创建了4个Button按钮、设置了不同的属性

width,height,relief,bg,bd,fg,state,bitmap,command,anchor,包含了大部分Butoon可用函数

#! /usr/bin/env python

#! encoding:utf-8

# Filename:Tkinter_Button_Test.py

from Tkinter import *

import tkMessageBox

root = Tk()

root.title("Button Test")

def callback():

    tkMessageBox.showinfo("Python command","人生苦短、我用Python")

"""

创建4个Button按钮、并设置width,height,relief,bg,bd,fg,state,bitmap,command,anchor

"""

Button(root, text="外观装饰边界附近的标签", width=19,relief=GROOVE,bg="red").pack()

Button(root, text="设置按钮状态",width=21,state=DISABLED).pack()

Button(root, text="设置bitmap放到按钮左边位置", compound="left",bitmap="error").pack()

Button(root, text="设置command事件调用命令", fg="blue",bd=2,width=28,command=callback).pack()

Button(root, text ="设置高度宽度以及文字显示位置",anchor = 'sw',width = 30,height = 2).pack()

root.mainloop()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python tkinter