Python Tkinter – 按钮

Tkinter教程,按钮小部件被用来在Python应用程序中添加各种类型的按钮。Python允许我们根据我们的要求来配置按钮的外观。各种选项可以根据要求进行设置或重置。
我们还可以将一个方法或函数与按钮联系起来,当按钮被按下时就会被调用。
使用按钮小部件的语法如下。

Python Tkinter Button 语法

W = Button(parent, options) 

下面列出了可能的选项清单:

SN 选项 描述
1 activebackground 当鼠标悬停在按钮上时,它代表按钮的背景。
2 activeforeground 当鼠标悬停在按钮上时,它代表按钮的字体颜色。
3 Bd 表示边界宽度,单位为像素。
4 Bg 它代表按钮的背景颜色。
5 Command 它被设置为函数调用,当函数被调用时,它将被安排。
6 Fg 表示按钮的前景颜色。
7 Font 按钮文本的字体。
8 Height 按钮的高度。对于文本行,高度以文本行数表示,对于图像,高度以像素数表示。
10 Highlightcolor 当按钮拥有焦点时,高亮的颜色。
11 Image 它被设置为显示在按钮上的图像。
12 justify 它说明了多个文本行的表现方式。它被设置为LEFT表示左对齐,RIGHT表示右对齐,CENTER表示中心。
13 Padx 在水平方向上对按钮进行额外的填充。
14 pady 在垂直方向上对按钮进行额外的填充。
15 Relief 它代表边界的类型。它可以是SUNKEN,RAISED,GROOVE,和RIDGE。
17 State 该选项设置为DISABLED,使按钮无反应。ACTIVE代表按钮的活动状态。
18 Underline 设置这个选项可以使按钮的文字下划线。
19 Width 按钮的宽度。对于文本按钮,它以字母数存在,对于图像按钮,它以像素数存在。
20 Wraplength 如果该值被设置为一个正数,文本行将被包裹以适应这个长度。

Python Tkinter Button 示例1

#python application to create a simple button

from tkinter import * 

top = Tk()

top.geometry("200x100")

b = Button(top,text = "Simple")

b.pack()

top.mainaloop()

输出:
Python Tkinter Button

Python Tkinter Button 示例2

from tkinter import * 

top = Tk()

top.geometry("200x100")

def fun():
    messagebox.showinfo("Hello", "Red Button clicked")

b1 = Button(top,text = "Red",command = fun,activeforeground = "red",activebackground = "pink",pady=10)

b2 = Button(top, text = "Blue",activeforeground = "blue",activebackground = "pink",pady=10)

b3 = Button(top, text = "Green",activeforeground = "green",activebackground = "pink",pady = 10)

b4 = Button(top, text = "Yellow",activeforeground = "yellow",activebackground = "pink",pady = 10)

b1.pack(side = LEFT)

b2.pack(side = RIGHT)

b3.pack(side = TOP)

b4.pack(side = BOTTOM)

top.mainloop()

输出:

Python Tkinter Button

Python Tkinter Button

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程