三、tk组件——按钮

本文最后更新于:2022年5月19日 下午

tk组件——按钮

  1. 按钮是非常重要的组件,可以响应点击事件来完成一些执行逻辑,按钮英文是“button”,它随处可见
  2. tkinter中有一个专门的类Button负责它
  3. ttk中的按钮和tkinter不一样

用法

增加一个button,方法如下:

1
B = Button ( master, option, ... )

源代码中Button类及其参数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Button(Widget):
"""Button widget."""

def __init__(self, master=None, cnf={}, **kw):
"""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
"""
Widget.__init__(self, master, 'button', cnf, kw)

参数详解:

参数 功能
activebackground Background color when the button is under the cursor.
activeforeground Foreground color when the button is under the cursor.
anchor Where the text is positioned on the button. See Section 5.5, “Anchors”. For example, anchor=tk.NE would position the text at the top right corner of the button.
bdborderwidth Width of the border around the outside of the button; see Section 5.1, “Dimensions”. The default is two pixels.
bgbackground 背景颜色
bitmap Name of one of the standard bitmaps to display on the button (instead of text).
command 当按钮被单击时触发的函数或者方法
cursor Selects the cursor to be shown when the mouse is over the button.
default tk.NORMAL is the default; use tk.DISABLED if the button is to be initially disabled (grayed out, unresponsive to mouse clicks).
disabledforeground Foreground color used when the button is disabled.
fgforeground Normal foreground (text) color.
font 按钮上显示的文字的字体
height Height of the button in text lines (for textual buttons) or pixels (for images).
highlightbackground Color of the focus highlight when the widget does not have focus.
highlightcolor The color of the focus highlight when the widget has focus.
highlightthickness Thickness of the focus highlight.
image Image to be displayed on the button (instead of text).
justify How to show multiple text lines: tk.LEFT to left-justify each line; tk.CENTER to center them; or tk.RIGHT to right-justify.
overrelief The relief style to be used while the mouse is on the button; default relief is tk.RAISED. See Section 5.6, “Relief styles”.
padx Additional padding left and right of the text. See Section 5.1, “Dimensions” for the possible values for padding.
pady Additional padding above and below the text.
relief Specifies the relief type for the button (see Section 5.6, “Relief styles”). The default relief is tk.RAISED.
repeatdelay See repeatinterval, below.
repeatinterval Normally, a button fires only once when the user releases the mouse button. If you want the button to fire at regular intervals as long as the mouse button is held down, set this option to a number of milliseconds to be used between repeats, and set the repeatdelay to the number of milliseconds to wait before starting to repeat. For example, if you specify “repeatdelay=500, repeatinterval=100” the button will fire after half a second, and every tenth of a second thereafter, until the user releases the mouse button. If the user does not hold the mouse button down at least repeatdelay milliseconds, the button will fire normally.
state Set this option to tk.DISABLED to gray out the button and make it unresponsive. Has the value tk.ACTIVE when the mouse is over it. Default is tk.NORMAL.
takefocus Normally, keyboard focus does visit buttons (see Section 53, “Focus: routing keyboard input”), and a space character acts as the same as a mouse click, “pushing” the button. You can set the takefocus option to zero to prevent focus from visiting the button.
text Text displayed on the button. Use internal newlines to display multiple text lines.
textvariable An instance of StringVar() that is associated with the text on this button. If the variable is changed, the new value will be displayed on the button. See Section 52, “Control variables: the values behind the widgets”.
underline Default is -1, meaning that no character of the text on the button will be underlined. If nonnegative, the corresponding text character will be underlined. For example, underline=1 would underline the second character of the button’s text.
width Width of the button in letters (if displaying text) or pixels (if displaying an image).
wraplength If this value is set to a positive number, the text lines will be wrapped to fit within this length. For possible values, see Section 5.1, “Dimensions”.

下面新建一个按钮示例:

1
2
3
4
5
6
7
import tkinter as tk  # 引入了该模块

root = tk.Tk() # 实例化Tk这个类
root.wm_title("OCR") # 设置窗口标题
b = tk.Button(root, text="这是按钮")
b.pack()
root.mainloop() # 让窗口一直执行,事件循环

运行结果如下:

新建按钮

其他参数的功能不一一赘述

按钮事件绑定

按钮可以执行相应的功能,可以理解为点击之后执行一个函数,那么就需要有一个事件响应用户点击并执行响应函数。事件绑定方式有以下几种:

1. command属性

声明按钮时包含command属性,command属性会接受一个函数名,函数名不要加双引号。尽量不要给函数加参数,如果要加参数,就必须用lambda

command 当按钮被单击之后执行的函数或方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import tkinter as tk  # 引入了该模块


def add_Label():
global root
s = tk.Label(root, text="新建的label")
s.pack()


root = tk.Tk() # 实例化Tk这个类
root.wm_title("OCR") # 设置窗口标题
root.wm_minsize(300, 300) # 设置窗口最小尺寸
b = tk.Button(root, text="这是按钮", command=add_Label)
b.pack()
root.mainloop() # 让窗口一直执行,事件循环

这里我们新建了一个函数add_Label,里面是全局变量root,作用是新建一个Label并增添到主窗口,然后我们在下面对其进行调用,将其赋给Button bcommand属性上,我们每点击一次b,就会执行一次command后面的函数,效果如下:

点击4次按钮

2. 使用bind方法。

首先,我们继续去源代码中找到bind函数,会发现bind方法是属于Misc类,且有三个参数:

  • sequence

    sequence是一串串联的事件模式的字符串。一个事件模式的形式是

    <MODIFIER-MODIFIER-TYPE-DETAIL>,其中:

    **MODIFIER**是以下修饰符之一:Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4, Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3,B3, Alt, Button4, B4, Double, Button5, B5 Triple, Mod1, M1

    **TYPE**则是表示类型,全部取值有:Activate, Enter, Map,ButtonPress, Button, Expose, Motion, ButtonReleaseFocusIn, MouseWheel, Circulate, FocusOut, Property, Colormap, Gravity Reparent, Configure, KeyPress, Key, Unmap, Deactivate, KeyRelease Visibility, Destroy,Leave

    **DETAIL**是按键和释放键的键位表。例如<Button-1>代表了鼠标左键单击<Control-Button-1>表示按Control键和鼠标左键;<Alt-A>表示按下AAlt键(KeyPress可以省略)。

  • func

    当上面的事件成立,就会执行这个函数

  • add

    一个额外的布尔参数ADD指定了FUNC是否会被另外调用,或者是否会被其他绑定的函数调用。是在其他绑定的函数之外再调用,还是它将取代之前的函数。

下面的源代码详细解释了各个参数的作用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
def bind(self, sequence=None, func=None, add=None):
"""Bind to this widget at event SEQUENCE a call to function FUNC.

SEQUENCE is a string of concatenated event
patterns. An event pattern is of the form
<MODIFIER-MODIFIER-TYPE-DETAIL> where MODIFIER is one
of Control, Mod2, M2, Shift, Mod3, M3, Lock, Mod4, M4,
Button1, B1, Mod5, M5 Button2, B2, Meta, M, Button3,
B3, Alt, Button4, B4, Double, Button5, B5 Triple,
Mod1, M1. TYPE is one of Activate, Enter, Map,
ButtonPress, Button, Expose, Motion, ButtonRelease
FocusIn, MouseWheel, Circulate, FocusOut, Property,
Colormap, Gravity Reparent, Configure, KeyPress, Key,
Unmap, Deactivate, KeyRelease Visibility, Destroy,
Leave and DETAIL is the button number for ButtonPress,
ButtonRelease and DETAIL is the Keysym for KeyPress and
KeyRelease. Examples are
<Control-Button-1> for pressing Control and mouse button 1 or
<Alt-A> for pressing A and the Alt key (KeyPress can be omitted).
An event pattern can also be a virtual event of the form
<<AString>> where AString can be arbitrary. This
event can be generated by event_generate.
If events are concatenated they must appear shortly
after each other.

FUNC will be called if the event sequence occurs with an
instance of Event as argument. If the return value of FUNC is
"break" no further bound function is invoked.

An additional boolean parameter ADD specifies whether FUNC will
be called additionally to the other bound function or whether
it will replace the previous function.

Bind will return an identifier to allow deletion of the bound function with
unbind without memory leak.

If FUNC or SEQUENCE is omitted the bound function or list
of bound events are returned."""

return self._bind(('bind', self._w), sequence, func, add)

下面看一下bind函数使用示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import tkinter as tk  # 引入了该模块

root = tk.Tk() # 实例化Tk这个类


def add_Label(event):
s = tk.Label(root, text="新建的label")
s.pack()


root.wm_title("OCR") # 设置窗口标题
root.wm_minsize(300, 300) # 设置窗口最小尺寸
b = tk.Button(root, text="这是按钮")
b.bind("<Button-1>", add_Label)
b.pack()
root.mainloop() # 让窗口一直执行,事件循环

注意这个时候我把root = Tk()写在了最前面,这里推荐这样做,当然也可以设置为global

上面的代码实现的功能和command一样,这里就不展示了

ttk中的Button

我们可以看到tkinter的按钮是真的不好看,与时俱进,这里介绍一下ttk。

ttk可以看作是tkinter的升级组件,就是为了完善一些tkinter的功能。通俗地说,tkinter有的,ttk也有;tkinter没有的,ttk也有。记住,这两的办法和属性很多都是一样的,按照下面的代码你可以导入这两个库,并看一下他俩生成的按钮的区别

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import tkinter as tk  # 引入了该模块
from tkinter import ttk

root = tk.Tk() # 实例化Tk这个类


def add_Label(event):
s = tk.Label(root, text="新建的label")
s.pack()


root.wm_title("OCR") # 设置窗口标题
root.wm_minsize(300, 300) # 设置窗口最小尺寸
b1 = tk.Button(root, text="tkinter按钮")
b2 = ttk.Button(root, text="ttk按钮1")
b3 = tk.ttk.Button(root, text="ttk按钮2")
b1.bind("<Button-1>", add_Label)
b1.pack()
b2.pack()
b3.pack()
root.mainloop() # 让窗口一直执行,事件循环

你可以直接使用ttk.Button(),也可以用这种形式tk.ttk.Button()

效果图:

image-20211123163108235

可以看到,明显ttk的按钮更加美观。但是注意一点,ttk和tkinter还是有一些区别的。如tkinter中的fg,bg属性在ttk中并不被支持,ttk是通过style这个对象来实现的,后面再说。


三、tk组件——按钮
https://jialiangz.github.io/2021/11/19/tkinter-3/
作者
爱吃菠萝
发布于
2021年11月19日
更新于
2022年5月19日
许可协议