Python tkinter Button 属性和方法介绍

Python Tkinter Button 属性和方法介绍

  • 1. Button
    • 1.1标准属性
    • 1.2 专有属性
    • 1.3方法
  • 2. Button属性和方法说明程序
    • 2.1 窗口代码
    • 2.2 属性和方法代码

1. Button

Button提供了用户触发特定功能的途径。Button的属性有:

1.1标准属性

            activebackground, activeforeground, anchor,
            background, bitmap, borderwidth, cursor,
            disabledforeground, font, foreground
            highlightbackground, highlightcolor,
            highlightthickness, image, justify,
            padx, pady, relief, repeatdelay,
            repeatinterval, takefocus, text,
            textvariable, underline, wraplength

1.2 专有属性

            command, compound, default, height,
            overrelief, state, width

以上属性来自于python tkinter的__init__文件。感兴趣的读者可以打开查看。

1.3方法

Button有2种方法:flash和invoke。flash的功能是让按钮文字和背景短暂闪烁。invoke的功能是调用指定按钮的回调函数,相当于按动了指定的按钮。

2. Button属性和方法说明程序

此程序说明了Button的所有属性和方法。可以通过下拉框选择,查看属性或者方法的效果以及如何设置属性。示例如下:
Python tkinter Button 属性和方法介绍_第1张图片
代码由两部分组成,第一部分是Tkinter窗口代码,第二部分是Button属性数据

2.1 窗口代码

# coding:utf8

import tkinter as tk
from tkinter.ttk import *
from Button_Parameter import *

cbx_para = None    # 属性下拉框
cbx_method = None  # 方法下拉框
lbl_status = None  # 输出说明性文字
lbl_code = None    #示例代码
lbl_result = None  #结果以及说明
btn_result = None  #示例按钮
frm_code = None    #代码Frame
frm_result = None  #结果Frame
init_para = {}     #记录按钮的初始设置
demo_image = None  #a.png图像
v_str = None       #StringVar变量


def GetInitParameter():
    global btn_result
    global init_para
    init_para = {}
    for item in Button_Parameter.parameter:
        index = item.split("/")[0]
        init_para[index] = btn_result[index]


def ClearParameter():
    global btn_result
    global init_para
    for item in Button_Parameter.parameter:
        index = item.split("/")[0]
        btn_result[index] = init_para[index]

def btn_command():
    global lbl_result
    lbl_result['text']="回调函数成功调用"
    lbl_result.grid(row=2,column=1)

def flash():
    global btn_result
    btn_result.flash()

def Para_Demo(*args):
    global cbx_para
    global lbl_code
    global lbl_status
    global lbl_result
    global frm_result
    global frm_code
    global demo_image
    global v_str

    index = cbx_para.current()
    lbl_result.grid_forget()
    #
    if index in Button_Parameter.Button_Para:
        ClearParameter()
        frm_code.grid(row=3, column=1, padx=5, pady=5)
        frm_result.grid(row=3, column=2, padx=5, pady=5)

        frm_code["text"] = Button_Parameter.parameter[index] + ":代码"
        frm_result["text"] = Button_Parameter.parameter[index] + ":效果"
        temp = Button_Parameter.Button_Para[index]
        dis_code = ""
        for item in range(1, len(temp[0])):
            dis_code = dis_code + temp[0][item] + "\n"

        lbl_code['text'] = dis_code
        for item in range(1, len(temp[0])):
            exec(temp[0][item])
        lbl_status['text'] = temp[1]
    else:
        frm_code.grid_forget()
        frm_result.grid_forget()

def Method_Demo(*args):
    global cbx_method
    global lbl_code
    global lbl_status
    global lbl_result
    global frm_result
    global frm_code

    index = cbx_method.current()
    lbl_result.grid_forget()
    #
    if index in Button_Parameter.Button_Method:
        ClearParameter()
        frm_code.grid(row=3, column=1, padx=5, pady=5)
        frm_result.grid(row=3, column=2, padx=5, pady=5)

        frm_code["text"] = Button_Parameter.method[index] + ":代码"
        frm_result["text"] = Button_Parameter.method[index] + ":效果"
        temp = Button_Parameter.Button_Method[index]
        dis_code = ""
        for item in range(1, len(temp[0])):
            dis_code = dis_code + temp[0][item] + "\n"

        lbl_code['text'] = dis_code
        for item in range(1, len(temp[0])):
            exec(temp[0][item])
        lbl_status['text'] = temp[1]
    else:
        frm_code.grid_forget()
        frm_result.grid_forget()


def center_window(root, width, height):
    screenwidth = root.winfo_screenwidth()
    screenheight = root.winfo_screenheight()
    size = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
    root.geometry(size)


def main():
    root = tk.Tk()
    # 属性下拉框
    # 按钮
    global frm_code
    global frm_result
    global v_str
    v_str = tk.StringVar()

    frm_top = tk.Frame(root)
    frm_top.grid(row=1, column=1, sticky="W", columnspan=3, pady=2)
    sp = Separator(root, orient='horizontal')
    sp.grid(row=2, column=1, columnspan=2, sticky="nwse")
    frm_code = tk.LabelFrame(root, text="")
    frm_code.grid(row=3, column=1, padx=10)
    sp = Separator(root, orient='vertical')
    sp.grid(row=3, column=2, sticky="nwse")
    frm_result = tk.LabelFrame(root, text="")
    frm_result.grid(row=3, column=2, pady=5)
    sp = Separator(root, orient='horizontal')
    sp.grid(row=4, column=1, columnspan=2, sticky="nwse")
    frm_bottom = tk.Frame(root)
    frm_bottom.grid(row=5, column=1, columnspan=3, sticky="w")

    nCbx_Height = 10
    tk.Label(frm_top, text="属性:").grid(row=1, column=1, sticky="e")
    global cbx_para
    global cbx_method

    # 属性
    txt = [Button_Parameter.parameter[item] + ":" + Button_Parameter.parameter_info[item] for item in range(len(Button_Parameter.parameter))]
    cbx_para = Combobox(frm_top, height=nCbx_Height, values=txt, width=38)
    cbx_para.bind("<>", Para_Demo)
    cbx_para.set(txt[0])
    cbx_para.grid(row=1, column=2)

    # 方法
    tk.Label(frm_top, text="方法:").grid(row=1, column=3, sticky="e", padx=10)
    txt = [Button_Parameter.method[item] + ":" + Button_Parameter.method_info[item]
           for item in range(len(Button_Parameter.method))]
    cbx_method = Combobox(frm_top, height=nCbx_Height, value=txt, width=20)
    cbx_method.bind("<>", Method_Demo)
    cbx_method.set(txt[0])
    cbx_method.grid(row=1, column=4)

    global lbl_status
    lbl_status = tk.Label(frm_bottom, text="", anchor="w", justify="left")
    lbl_status.grid(row=1, column=1, sticky="w")

    global lbl_code
    lbl_code = tk.Label(frm_code, text="", justify="left")
    lbl_code.grid(row=1, column=1)

    global btn_result
    btn_result = tk.Button(frm_result)
    btn_result.grid(row=1, column=1)
    global lbl_result
    lbl_result = tk.Label(frm_result, text="", justify="left", pady=5)
    lbl_result.grid(row=1, column=2)

    GetInitParameter()
    global demo_image
    demo_image = tk.PhotoImage(file='a.PNG')
    frm_result.grid_forget()
    frm_code.grid_forget()

    root.title("Tkinter 按钮使用说明")
    center_window(root, 600, 280)
    root.mainloop()


if __name__ == "__main__":
    main()
"""tkinter中关于Button的注释
        Construct a button widget with the parent MASTER.

        STANDARD OPTIONS

            activebackground, activeforeground, anchor,
            background, bitmap, borderwidth, cursor,
            disabledforeground, font, foreground
            highlightbackground, highlightcolor,
            highlightthickness, image, justify,
            padx, pady, relief, repeatdelay,
            repeatinterval, takefocus, text,
            textvariable, underline, wraplength

        WIDGET-SPECIFIC OPTIONS

            command, compound, default, height,
            overrelief, state, width
"""


2.2 属性和方法代码

Button_Parameter.py

#coding:utf8

class Button_Parameter():
    #Button 参数名称
    parameter=["activebackground", "activeforeground", "anchor", "background/bg",
               "bitmap", "borderwidth/bd", "command","compound",
               "cursor", "default","disabledforeground", "font",
               "foreground/fg","height","highlightbackground", "highlightcolor",
                "highlightthickness","image","justify","overrelief",
               "padx", "pady", "relief","repeatdelay",
               "repeatinterval","state","takefocus","text",
               "textvariable", "underline","width", "wraplength"]

    #Button 参数说明
    parameter_info=["背景颜色", "文本颜色", "锚定文字或者图片", "背景颜色",
               "显示bitmap", "边框宽度","设定回调函数","同时显示文字和图片的方法",
                "光标样式","设置默认方式","禁止时的背景颜色", "字体",
                "文字或者bitmap颜色", "高度","未获得焦点时边框颜色","获得焦点时边框颜色",
                "焦点边框宽度","图片","多行文字时对齐方式","鼠标经过按钮时的3D效果",
                "x方向上内边距", "y方向上内边距", "边框效果","重复按下启动时间",
                "重复按下延时间隔","状态", "使用Tab获得焦点", "显示文字",
                "StringVar变量与按钮相关联", "指定字符下划线", "宽度", "折叠多行"
                    ]
    #Button 方法
    method=["flash","invoke"]
    #Button 方法说明
    method_info=["按钮出现闪烁","调用回调函数"]
    #Button 说明,包括序号、代码说明、代码、运行效果
    Button_Para = {
        0: [["activebackground:", "btn_result['activebackground']='red'",
             "btn_result['text']='activebackground:背景颜色'"],
            "activebackground:定义按钮被按下时的背景颜色。"],
        1: [["activeforeground:", "btn_result['activeforeground'] = 'blue'", "btn_result['state'] = 'active'",
             "btn_result['text']='activeforeground:文本颜色'"],
            "activeforeground:定义按钮被按下时文字的颜色。"],
        2: [["anchor:", "btn_result['height']=2", "btn_result['anchor']='se'", "btn_result['width']=30",
             "btn_result['text']='anchor:按钮在右下角SE'"],
            "anchor:指定如何对齐文字或者图片\nanchor与justify是不同的。\njustify针对的是多行文本的对齐\nanchor针对的是文本在按钮中放置的位置\nanchor可以设置为n,s,w,e或者组合,也可以是center"],
        3: [["background/bg:", "btn_result['text']='绿色背景'", "btn_result['bg']='green'",
             "btn_result['text']='bg:背景颜色是绿色'"],
            "background/bg:指定按钮的背景颜色"],
        4: [["bitmap:", "btn_result['bitmap']='error'"],
            "bitmap:显示位图\n1)使用系统自带的bitmap,直接输入名字即可。比如bitmap=’error’\n2)使用自定义的bitmap,在路径前面加上’@’即可"
            ],
        5: [["borderwidth/bd:", "btn_result['bd']=20", "btn_result['bg']='lightblue'", "btn_result['text']='bd:边框=20'"],
            "bd:设置文本到Label边界的宽度\nbd参数相当于设置了padx和pady参数"
            ],
        6: [["command:", "btn_result['command']=btn_command","btn_result['text']='回调函数'"],
            "compound:设置回调函数\n在按钮被松开后调用"
            ],
        7:  [["compound:", "#demo_image = tk.PhotoImage(file='a.PNG')", "btn_result['image']=demo_image",
             "btn_result['text']='文字在图片下方'", "btn_result['compound']=tk.TOP"],
            "compound:设置图片相对文字的位置\n可以设置为bottom,top,center,right,left\nbottom代表的是图片相对文字的位置\n实际使用中要去掉第一行代码的注释"
            ],
        8: [["cursor:", "btn_result['cursor']='watch'", "btn_result['text']='鼠标经过按钮时的光标'"],
            "cursor:鼠标经过按钮时的光标"
            ],
        9: [["default:", "btn_result['default']=tk.ACTIVE","btn_result['text']='Default状态'"],
            "default:按钮Default状态。有三种状态:active,disabled,或normal。\nDefault状态会在最外侧增加额外的黑色边框"],
        10: [["disabledforeground:", "btn_result['state']=tk.DISABLED", "btn_result['disabledforeground']='red'",
             "btn_result['text']='按钮禁止状态,文字是红色的'"],
            "disabledforeground:按钮禁止状态下文字的颜色"],
        11: [["font:", "btn_result['font']=('宋体',20,)", "btn_result['text']='font=(\"宋体\",20,)'"],
            "font:设置文本字体。\n一个按钮只能用一种字体。\n字体定义可以使用三元组(字体名称,大小,修饰)\n也可以使用Font类"
            ],
        12: [["foreground/fg:", "btn_result['text']='红色文本'", "btn_result['fg']='red'"],
             "fg:设置按钮文本的颜色\n要求按钮的状态是tk.NORMAL"],
        13: [["height:", "btn_result['text']='height=10'", "btn_result['height']=10"],
             "height:设置按钮的高度,一般与width配合使用"],
        14: [["highlightbackground:", "btn_result['highlightbackground']='blue'","btn_result['text']='highlightbackground在Button无效'"],
             "highlightbackground:未获得焦点时边框颜色"],
        15: [["highlightcolor:", "btn_result['highlightcolor']='blue'","btn_result['text']='highlightcolor在Button无效'"],
             "highlightcolor:获得焦点时边框颜色"],
        16: [["highlightthickness:", "btn_result['highlightthickness']=10","btn_result['text']='焦点边框宽度'"],
             "highlightthickness:焦点边框宽度"],
        17: [["image:", "#demo_image = tk.PhotoImage(file='a.PNG')", "btn_result['image']=demo_image"],
             "image:在按钮上显示图片"],
        18: [["justify", "btn_result['justify']=tk.LEFT", "btn_result['text']='文字左对齐\\n第二行'"],
             "justify:多行文本的对齐方式\n支持left,right,center"],
        19: [["overrelief", "btn_result['overrelief']=tk.LEFT", "btn_result['text']='鼠标经过按钮时的3D效果'"],
             "overrelief:鼠标经过按钮时的3D效果\n可设为flat, groove, raised, ridge, solid, or sunken"],
        20: [["padx:", "btn_result['text']='padx=5'", "btn_result['width']=30", "btn_result['padx']=5"],
             "padx:设置文本到按钮边框水平方向距离,常与pady配合使用"],
        21: [["pady:", "btn_result['text']='pady=5'", "btn_result['pady']=5"],
             "pady:设置文本到按钮边框垂直方向的距离,常与padx配合使用"],
        22: [["relief:", "btn_result['text']='边框修饰效果'", "btn_result['bd']=10", "btn_result['relief']='raised'"],
             "relief:按钮边框的修饰效果\n可设为flat, groove, raised, ridge, solid, or sunken"],
        23: [["repeatdelay", "btn_result['repeatdelay']=1000", "btn_result['repeatinterval']=300","btn_result['command']=btn_command",
                "btn_result['text']='repeatdelay'"],
             "repeatdelay:设置重复按下启动时间\n当按钮被持续按下,在一定间隔后会触发调用回调函数。调用的间隔在repeatinterval设置"],
        24: [["repeatinterval", "btn_result['repeatdelay']=1000", "btn_result['repeatinterval']=300","btn_result['command']=btn_command",
              "btn_result['text']='repeatinterval'"],
             "repeatinterval:设置重复按下延时间隔\n当按钮被持续按下,在一定间隔后会触发调用回调函数。调用的间隔在repeatinterval设置"],
        25: [["state", "btn_result['state']=tk.NORMAL", "btn_result['text']='按钮正常状态'"],
             "state:设置按钮状态\n可设为active, disabled, normal"],
        26: [["takefocus:", "btn_result['takefocus']=True", "btn_result['text']='按钮获得输入焦点'"],
             "takefocus:支持获得输入焦点。"],
        27: [["text:", "btn_result['text']='按钮显示的文本'"],
             "text:为按钮要显示的文本"],
        28: [["textvariable:", "v_str.set('通过textvariable改变按钮文本')", "btn_result['textvariable']=v_str"],
             "textvariable:定义与按钮文本相关联的变量\n该变量的变化会反应在按钮中"],
        29: [["underline:", "btn_result['underline']=4", "btn_result['text']='Hello World!'"],
             "underline:在指定字母下面显示下划线"],
        30: [["width:", "btn_result['width']=30", "btn_result['text']='width=30'"],
             "width:定义按钮宽度\n常与height属性配合使用"],
        31: [["wraplength:", "btn_result['wraplength']='50'", "btn_result['text']='这个很长的文本会被折行显示wraplength=30'"],
             "wraplength:定义折行显示\n超过wraplength定义的长度的文字会折行显示\nwraplength的单位是像素,不是文字数目"]
    }

    #Button 方法代码说明
    Button_Method = {
        0:[["flush:","btn_result['activebackground']='red'","btn_result['activeforeground'] = 'blue'",
            "btn_result['text'] = '按动按钮,出现闪烁效果'","btn_result['command']=flash"],
           "flush:按钮闪烁。\n需要设置activebackground和activeforeground,否则没闪烁效果"],
        1:[["invoke:","btn_result['text'] = '调用其他按钮的回调函数'"],
           "invoke:直接调用回调函数\n本示例没有实现此功能"],
    }

你可能感兴趣的:(Python,tkinter,python,Tkinter)