Tkinter-第一章至第五章-初识Tkinter及Label与Button控件

前言

本文章主要讲解Python中的Tkinter标准库。
第一章:认识Tkinter
第二章:控件的通用属性
第三章:Label-标签控件
第四章:pack-grid-place-控件布局管理
第五章:Button-按钮控件


第一章 初识tkinter

1-1 学习资源

名称说明链接
GeeksforGeeks一个类似于菜鸟教程的资源网站,但内容与菜鸟教程还是有些区别,右侧链接直达tkiner教程Python Tkinter - GeeksforGeeks
菜鸟教程菜鸟教程有tkinter教程,但只是简单介绍了一下并不全面,推荐使用GeeksforGeeks网站中的教程菜鸟教程-tkinter
菜鸟鸭对于tkiner中的控件介绍比较全面,也有示例代码,Python 3 - Tkinter
Python官网简单介绍了tkiner及其控件,也有案例代码,但介绍的并不全面, 可以结合GeeksforGeeks和菜鸟鸭里的教程学习Tk图形用户界面(GUI) — Python 3.13.5 文档
Tkinter布局助手一款为tkinter打开的开发工具,可以拖拽组件进行布局Tkinter布局助手
maliang一个基于 tkinter 且控件都由 Canvas 绘制的轻量级 UI 框架项目主页 - maliang
ttkbootstraptkinter的超强主题扩展,可实现受Bootstrap启发的按需现代平面风格主题。ttkbootstrap - ttkbootstrap
CustomTkinter一个基于tkinter的现代化和可自定义化的Ui扩展库https://customtkinter.tomschimansky.com/
C语言程序网这个网站中有tkinter的常用控件教程,也比较详细,也有案例,但没有ttk的控件教程Tkinter教程(非常详细) - C语言中文网

1-2 tkiner简介

1.tkinter是什么

​ tkinter是Python中的一个标准的图形用户界面库(Graphical User Interface即GUI),它提供了一个快速且容易的方案来创建一个桌面应用程序。tkinter提供了一系列的控件,比如按钮(Button)、标签(Label)、单行与多行文本输入框(Entry与Text)、菜单(Menu)等等,这些控件可以被用来创建交互式用户界面。tkinter也支持事件驱动编程,即根据用户的点击或按键等事件来执行相应操作。

​ tkinter中有一个加强版的控件模块叫做ttk模块,这个模块不但包含了原来tkinter中的大多数控件,也增加了几个新的控件(比如notebook控件),而且ttk模块中的控件比原始的tkinter控件更加美观,更加现代化。

2.tkinter的应用场景

(1)轻量级桌面工具开发
  • 个人效率工具:如批量文件重命名工具、文本内容提取器、日志分析小助手、简易密码生成器等。例如,通过 Tkinter 快速搭建一个界面,用户选择文件夹后,工具自动按规则修改文件名,界面只需几个按钮、输入框和 Label 标签即可实现。
  • 办公辅助工具:如 Excel 数据快速处理工具(格式转换、重复值清理)、PDF 页面提取 / 合并工具、邮件模板发送器等。这类工具针对办公场景中的重复劳动,通过简单的 GUI 让非技术人员也能操作,无需编写代码。
(2)内部业务辅助系统
  • 数据录入与管理系统:例如,小型销售团队的客户信息录入系统,界面包含表单(输入框、下拉菜单、复选框)和提交按钮,数据可存储在本地数据库(如 SQLite)中,通过 Tkinter 快速实现数据的增删改查。
  • 流程化工具:如项目进度跟踪表(团队成员更新进度后,界面实时展示)、内部审批流程简易界面(填写申请信息后提交给管理员)等,满足团队内部低频次、轻量的协作需求。
(3)教学与学习场景
  • 编程教学示例:教师在讲解 “事件驱动编程”“界面布局” 等概念时,可通过 Tkinter 编写简单案例(如计算器、猜数字游戏),让学生直观看到代码与界面的关联。
  • 学生实践项目:初学者通过 Tkinter 开发小型项目(如贪吃蛇游戏、简易记事本、个人日程表),巩固 Python 基础语法(函数、类、循环)和 GUI 逻辑,培养编程思维。
(4)快速原型验证
  • 产品原型演示:例如,在开发一款复杂软件前,先用 Tkinter 制作简易原型,模拟核心功能(如登录流程、数据展示方式),用于团队内部讨论或向客户演示需求,收集反馈后再进行正式开发。
  • 功能可行性测试:针对某个具体功能(如实时数据可视化、文件格式解析),用 Tkinter 快速构建界面,测试功能逻辑是否可行,降低正式开发的风险。
(5)科研与实验工具
  • 实验数据展示工具:例如,将传感器采集的实时数据(如温度、湿度)通过 Tkinter 界面实时显示(用 Label 展示数值、Canvas 绘制简单曲线),方便实验人员监控。
  • 设备控制界面:通过 Tkinter 按钮、滑块等控件,发送指令控制连接的硬件设备(如调节电机转速、控制灯光开关),界面无需美观,只需稳定实现交互即可。
(6)小型游戏开发
  • 益智小游戏:如猜数字、拼图、简易贪吃蛇、俄罗斯方块等,通过 Tkinter 的 Canvas 控件绘制游戏元素,绑定键盘 / 鼠标事件实现交互,适合初学者练习 GUI 与游戏逻辑结合。

1-3 tkinter入门

1.创建tkinter用户界面程序

# 第一步 导入tkinter模块,tkinter模块是创建GUI控件的基础模块,必须导入
import tkinter as tk

# 第二步 创建主窗口,我们也可以叫它根窗口(相当于一个可以装入其他控件的容器)
root = tk.Tk()

# 第三步 设置窗口属性(这里我们设置主窗口root的属性)
root.geometry("800x600+600+300")
root.title("第一个用户界面")

# 第四步 向主窗口中加入控件(这里我们加入一个标签控件Label),其中第一个参数root表示控件的父窗口,第二个参数text表示标签的文字内容
label = tk.Label(root, text="这是一个标签控件")

# 第五步 包装控件,就是布局这个控件在主窗口的位置和在主窗口中显示这个控件
label.pack()

# 第六步 启动tkinter应用程序
root.mainloop()

如果你熟悉面向对象,我们还可以使用类来设计程序窗口

import tkinter as tk

class Application(tk.Tk):
    def __init__(self):
        super().__init__()
        self.create_widgets()

    def create_widgets(self):
        self.label = tk.Label(master=self, text="这是一个标签控件")
        self.label.pack(")



app = Application()
app.geometry("800x600+600+300")
app.title("第一个用户界面")
app.mainloop()

在这里插入图片描述

2.核心细节

tkinter中的Tk()类用来创建应用程序的主窗口,使用规则如下:

root = tk.Tk(screenName=None, baseName=None, className=‘Tk’, useTk=1)

参数含义(一般不会使用下面这些参数):

参数名类型作用默认值
className字符串设置窗口内部类名,用于样式配置"Tk"
screenName字符串指定显示屏幕(多显示器环境)当前屏幕
baseName字符串设置应用基础名称,用于资源查找className
useTk布尔值是否使用 Tk 工具包True

className

  • 示例:

    root = tk.Tk(className="MyApp")
    
  • 注意:在某些系统中,此名称会影响窗口的默认样式和标题栏外观。

screenName

  • 格式"displayname""hostname:displaynumber"

  • 示例

    # 在第二台显示器上显示窗口(X Window 系统)
    root = tk.Tk(screenName=":1.0")
    
  • 注意:Windows 系统通常忽略此参数,仅在 Unix/Linux 系统的 X Window 环境中有效。

baseName

  • 示例

    root = tk.Tk(baseName="myapp")
    

useTk

  • 示例:

    root = tk.Tk(useTk=False)  # 创建一个不使用 Tk 工具包的窗口
    

3.常用配置方法(等价于参数设置)

虽然 Tk() 构造函数的直接参数较少,但可以通过以下方法进一步配置窗口:

(1)窗口标题与大小
root.title("应用标题")  # 设置窗口标题
root.geometry("400x300+100+100")  # 宽400px,高300px,位置(100, 100)
root.minsize(200, 200)  # 最小尺寸
root.maxsize(800, 600)  # 最大尺寸
root.resizable(True, False)  # 允许水平调整,禁止垂直调整
(2)窗口状态与属性
root.iconify()  # 最小化窗口
root.deiconify()  # 恢复窗口
root.attributes("-alpha", 0.9)  # 透明度90%,值越小越透明,当值等于0时完全透明
root.attributes("-topmost", True)  # 窗口置顶
root.attributes("-transparentcolor", "#0000FF")  # 透明色仅限Windows
root.attributes('-disabled', 1)  # 禁用窗口交互
root.attributes('-fullscreen', 1)  # 全屏模式
root.attributes('-toolwindow', 1)  # 工具窗口样式
root.state("zoomed")  # 最大化窗口(Windows/Linux)
root.state("iconic")  # 最小化窗口

4.特殊参数示例

(1)多显示器支持
import tkinter as tk

# 在第二台显示器上创建窗口(需系统支持)
root = tk.Tk(screenName=":0.1")  # X Window 系统中第二个显示器
root.title("跨屏应用")
root.mainloop()

5.注意事项

(1)参数与方法的区别
  • 构造函数参数(如 className)在创建窗口时一次性设置。
  • 配置方法(如 title()geometry())可以在窗口创建后随时调用。
(2)平台差异
  • 部分参数(如 screenName)仅在特定平台(如 Linux)有效。
  • 窗口样式和行为可能因操作系统而异。
(3)高级配置
  • 对于复杂的窗口配置,推荐使用方法调用而非构造函数参数,以提高代码可读性。

1-4 Tk类的核心属性和方法

1.root窗口的核心属性

  • title:窗口标题(字符串),可通过 root.title("标题") 直接赋值修改。
  • geometry:窗口尺寸和位置(字符串,格式如 "宽x高+X+Y"),如 root.geometry("500x300+100+200")
  • minsize:窗口最小尺寸(宽、高,整数),通过 root.minsize(width, height) 设置。
  • maxsize:窗口最大尺寸(宽、高,整数),通过 root.maxsize(width, height) 设置。
  • resizable:窗口是否可调整大小(布尔值),root.resizable(width=True, height=False) 控制宽 / 高是否可拉伸。
  • bg/background:窗口背景颜色(字符串,如 "red"#RRGGBB)。
  • iconbitmap:窗口图标(字符串,.ico 文件路径),通过 root.iconbitmap("icon.ico") 设置。
  • state:窗口状态(字符串,"normal" 正常 /"iconic" 最小化 /"zoomed" 最大化),可通过 root.state("zoomed") 切换。
  • protocol:窗口协议绑定(如关闭窗口事件),通过 root.protocol("WM_DELETE_WINDOW", func) 绑定回调。

2.root窗口的核心方法

以下方法按功能分类,包含功能、参数、返回值说明:

(1)窗口基本设置
  • title(string)
    • 功能:设置窗口标题。
    • 参数:string(字符串),窗口标题文本。
    • 返回值:无。
  • geometry(string)
    • 功能:设置窗口尺寸和位置(格式:"宽x高+X+Y",如 "500x300+100+200"X/Y 为屏幕坐标)。
    • 参数:string(字符串),尺寸和位置信息。
    • 返回值:无。
  • minsize(width, height)
    • 功能:设置窗口最小宽高(小于该值无法缩小)。
    • 参数:width(整数,最小宽度)、height(整数,最小高度)。
    • 返回值:无。
  • maxsize(width, height)
    • 功能:设置窗口最大宽高(大于该值无法放大)。
    • 参数:width(整数,最大宽度)、height(整数,最大高度)。
    • 返回值:无。
  • resizable(width, height)
    • 功能:控制窗口是否可调整宽 / 高。
    • 参数:width(布尔值,True 允许调整宽度)、height(布尔值,True 允许调整高度)。
    • 返回值:无。
  • iconbitmap(bitmap)
    • 功能:设置窗口图标(仅 Windows 系统有效)。
    • 参数:bitmap(字符串,.ico 图标文件路径)。
    • 返回值:无。
  • state(newstate)
    • 功能:设置窗口状态。
    • 参数:newstate(字符串,"normal" 正常 /"iconic" 最小化 /"zoomed" 最大化)。
    • 返回值:无。
(2)坐标与尺寸获取
  • winfo_x()
    • 功能:获取窗口相对于父容器(通常是屏幕)的 X 坐标(相对坐标)。
    • 参数:无。
    • 返回值:整数,X 坐标(像素)。
  • winfo_y()
    • 功能:获取窗口相对于父容器的 Y 坐标(相对坐标)。
    • 参数:无。
    • 返回值:整数,Y 坐标(像素)。
  • winfo_rootx()
    • 功能:获取窗口左上角在屏幕上的绝对 X 坐标。
    • 参数:无。
    • 返回值:整数,屏幕绝对 X 坐标(像素)。
  • winfo_rooty()
    • 功能:获取窗口左上角在屏幕上的绝对 Y 坐标。
    • 参数:无。
    • 返回值:整数,屏幕绝对 Y 坐标(像素)。
  • winfo_width()
    • 功能:获取窗口当前宽度。
    • 参数:无。
    • 返回值:整数,宽度(像素)。
  • winfo_height()
    • 功能:获取窗口当前高度。
    • 参数:无。
    • 返回值:整数,高度(像素)。
  • winfo_screenwidth()
    • 功能:返回当前屏幕的总宽度(以像素为单位)。
    • 参数:无。
    • 返回值:整数,表示屏幕的像素宽度。例如,在 1920×1080 分辨率的显示器上返回 1920。
  • winfo_screenheight()
    • 功能:返回当前屏幕的总高度(以像素为单位),包含任务栏、顶部菜单等所有区域。
    • 参数:无。
    • 返回值:整数,表示屏幕的像素宽度。例如,在 1920×1080 分辨率的显示器上返回 1080。
  • 如何正确的获取坐标
    • winfo_x()/winfo_y()等 需要在控件实际渲染后才能返回正确值。
    • mainloop() 是 Tkinter 渲染控件的触发点,在此之前调用位置方法会返回 0,所以必须在 mainloop() 启动后(即控件完成渲染),通过事件触发(如按钮点击、窗口加载完成)来获取坐标。
(3)事件与绑定
  • bind(event, handler)
    • 功能:为窗口绑定事件(如鼠标点击、键盘按键)。
    • 参数:event(字符串,事件标识符,如 <Button-1> 鼠标左键点击);handler(函数,事件触发时的回调函数)。
    • 返回值:无。
  • unbind(event)
    • 功能:解除窗口绑定的事件。
    • 参数:event(字符串,需解除的事件标识符)。
    • 返回值:无。
  • protocol(name, func)
    • 功能:绑定窗口协议(如关闭窗口事件)。
    • 参数:name(字符串,协议名称,常用 "WM_DELETE_WINDOW" 表示窗口关闭);func(函数,协议触发时的回调函数)。
    • 返回值:无。
(4)窗口显示与控制
  • mainloop()
    • 功能:启动窗口事件循环(程序进入阻塞状态,等待用户交互)。
    • 参数:无。
    • 返回值:无。
  • withdraw()
    • 功能:隐藏窗口(不销毁,可通过 deiconify() 恢复)。
    • 参数:无。
    • 返回值:无。
  • deiconify()
    • 功能:显示被 withdraw() 隐藏的窗口。
    • 参数:无。
    • 返回值:无。
  • iconify()
    • 功能:将窗口最小化(缩放到任务栏)。
    • 参数:无。
    • 返回值:无。
  • destroy()
    • 功能:销毁窗口(释放资源,程序退出)。
    • 参数:无。
    • 返回值:无。
(5)其他常用方法
  • config(**options)

    • 功能:批量设置窗口属性(如背景色、标题等)。
    • 参数:** options(关键字参数,如 bg="blue", title="新标题")。
    • 返回值:无。
  • update()

    • 功能:强制更新窗口(处理未完成的事件,避免界面卡顿)。
    • 参数:无。
    • 返回值:无。
  • update_idletasks()

    • 功能:更新窗口的闲置任务(如刷新控件显示)。
    • 参数:无。
    • 返回值:无。
  • after(parent, ms, function = None, *args)

    • 功能:是一个核心函数,用于实现 延迟执行定时任务。它允许你在指定的时间后执行代码,或周期性 地重复执行代码,这在创建动画、定时更新数据或实现复杂交互时非常有用

    • 参数: parent: is the object of the widget or main window whichever is using this function.
      ms: 多少毫秒后执行函数,1000 毫秒 = 1 秒
      function: 调用执行的函数
      args: 传递给回调函数的参数。

    • 返回值:返回一个唯一的标识符(整数),可用于取消任务(通过 after_cancel())。

    • 延迟执行(一次性任务)

      import tkinter as tk
      
      root = tk.Tk()
      
      def say_hello():
          print("Hello, world!")
      
      # 延迟 2000 毫秒(2 秒)后执行 say_hello 函数
      root.after(2000, say_hello)
      
      root.mainloop()
      
    • 传递参数

      def update_label(text):
          label.config(text=text)
      
      # 3 秒后更新标签文本
      root.after(3000, update_label, "新文本")
      
    • 周期性任务(定时器),通过在回调函数中再次调用 after() 实现循环

      import tkinter as tk
      
      root = tk.Tk()
      counter = 0
      
      def update_counter():
          global counter
          counter += 1
          label.config(text=f"计数: {counter}")
          # 每 1000 毫秒(1 秒)调用一次自身
          root.after(1000, update_counter)
      
      label = tk.Label(root, text="计数: 0")
      label.pack(pady=20)
      
      # 启动计时器
      update_counter()
      
      root.mainloop()
      
    • 注意事项

      • after() 任务在 Tkinter 的主事件循环中执行,若任务耗时过长,会阻塞 UI 更新。
      • 避免在回调函数中执行耗时操作,如文件读写、网络请求等,这些应使用线程处理。
      • 使用 after_cancel(task_id) 取消已计划但未执行的任务

1-5 tkinter控件及加强版tkinter模块ttk

​ 在我们把根窗口(也就是主窗口)建立好之后,我们就需要在根窗口中添加我们想要的控件以及布局。在tkinter中,我们可以通过导入import tkinter as tk创建想要加入到根窗口的控件,也可以通过from tkinter import ttk创建控件,两者都可以创建控件且控件的名称是相同的,但tkk模块相较于原始的tkinter,通过tkk模块创建的组件样式更加美观,而且还新加入了新控件。

1.原始tkinter与加强版tkinter模块ttk的区别(以Button按钮控件为例)

import tkinter as tk
from tkinter import ttk


class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("比较原始tkinter和加强版tkinter模块ttk的区别(以Button按钮控件为例)")
        self.geometry("800x600")

        self.create_widgets()

    def create_widgets(self):
        """创建要添加的控件"""
        # 创建原始tkinter的Button,并取名为tkButton
        tkButton = tk.Button(self, text="原始tkinter的Button")
        # 布局控件并在主窗口中显示这个控件
        tkButton.pack(pady=20)

        # 创建加强版tkinter的Button,并取名为tkButton
        ttkButton = ttk.Button(self, text="加强版ttk模块中的Button")
        # 布局控件并在主窗口中显示这个控件
        ttkButton.pack()


if __name__ == '__main__':
    root = App()
    root.mainloop()

在这里插入图片描述

上边的按钮是原来的tkinter中Button的默认样式,而下边的按钮是加强版的按钮默认样式,在此我们可以看出加强版的控件样式更加好看。

2.tkinter中的常用控件

控件名称控件中文名称控件的作用示例
Button()按钮用于触发特定的函数或操作,可包含文本或图像。单击时执行一个动作,如鼠标移过、按下、释放,以及键盘操作等事件在这里插入图片描述
Canvas()画布用于绘制图形、图表、图像,或实现自定义的用户界面元素。在这里插入图片描述
Checkbutton()复选框允许用户从多个选项中选择零个或多个选项。一组复选框可以成组,允许选择任意个,类似HTML中的复选框在这里插入图片描述
Entry()单行文本输入框用于获取用户的单行文本输入。在这里插入图片描述
Frame()框架作为容器控件,用于组织和管理其他控件的布局。在这里插入图片描述
Label()标签用于显示文本或图像,通常用于提供说明或显示程序状态。在这里插入图片描述
Listbox()列表框显示一个选项列表,用户可以从中选择一个或多个选项。在这里插入图片描述
Menu()菜单用于创建菜单栏、下拉菜单和弹出菜单。在这里插入图片描述
Menubutton()菜单按钮用于创建下拉式、层叠式菜单的按钮,用户点击后会显示关联的菜单选项。在这里插入图片描述
OptionMenu()选项菜单用于创建下拉式选择菜单,提供预定义的选项列表,用户可从中选择一个值。本质是 MenubuttonMenu 的组合,简化了单选菜单的创建。在这里插入图片描述
Message()消息框用于显示多行文本,类似于 Label,但能自动换行。在这里插入图片描述
Radiobutton()单选按钮用于在多个互斥选项中选择一个选项。在这里插入图片描述
Scale()滑块允许用户通过拖动滑块在一定范围内选择数值。可以设置起始值和结束值,会显示当前位置的精确值在这里插入图片描述
Scrollbar()滚动条用于为 Canvas、Text、Listbox 等控件添加滚动功能。在这里插入图片描述
Text()多行文本框用于显示和编辑多行文本,支持文本格式化。在这里插入图片描述
Toplevel()顶级窗口创建一个独立的顶级窗口,通常用于对话框或弹出窗口。是一个容器控件,类似Frame,可以为其他控件提供单独的容器在这里插入图片描述
Spinbox()数值选择框允许用户从预定义的值列表或数值范围内选择值。在这里插入图片描述
PanedWindow()窗格窗口用于创建可调整大小和窗口布局管理的控件,其中也可以放置其他控件。在这里插入图片描述
LabelFrame()标签框架带标签的框架,用于组织相关的控件。在这里插入图片描述

3.加强版tkinter模块ttk中的常用控件

控件名称控件中文名称控件的作用示例
ttk.Button()主题按钮功能与 tkinter.Button 类似,但外观更现代,支持主题。在这里插入图片描述
ttk.Checkbutton()主题复选框功能与 tkinter.Checkbutton 类似,外观更现代。在这里插入图片描述
ttk.Combobox()组合框下拉列表框,用户可以从预定义选项中选择或输入自定义值。在这里插入图片描述
ttk.Entry()主题单行输入框功能与 tkinter.Entry 类似,但外观更现代,支持主题。在这里插入图片描述
ttk.Frame()主题框架功能与 tkinter.Frame 类似,外观更现代。在这里插入图片描述
ttk.Label()主题标签功能与 tkinter.Label 类似,外观更现代。在这里插入图片描述
ttk.LabelFrame()主题标签框架功能与 tkinter.LabelFrame 类似,外观更现代。在这里插入图片描述
ttk.Menubutton()主题菜单按钮用于创建下拉菜单的按钮。在这里插入图片描述
ttk.OptionMenu()选项菜单用于创建下拉式选择菜单,提供预定义的选项列表,用户可从中选择一个值。本质是 MenubuttonMenu 的组合,简化了单选菜单的创建。在这里插入图片描述
ttk.Notebook()选项卡控件创建包含多个选项卡的界面,用户可以通过点击选项卡切换内容。在这里插入图片描述
ttk.Progressbar()进度条显示操作的进度,有确定和不确定两种模式。在这里插入图片描述
ttk.Radiobutton()主题单选按钮功能与 tkinter.Radiobutton 类似,外观更现代。在这里插入图片描述
ttk.Scrollbar()主题滚动条功能与 tkinter.Scrollbar 类似,外观更现代。在这里插入图片描述
ttk.Separator()分隔符用于在界面中创建水平或垂直的分隔线,分隔不同的控件组。在这里插入图片描述
ttk.Sizegrip()尺寸调整手柄用于调整窗口大小的小部件,通常位于窗口的右下角。在这里插入图片描述
ttk.Spinbox()主题数值选择框功能与 tkinter.Spinbox 类似,外观更现代。在这里插入图片描述
ttk.Treeview()树视图用于显示层次结构数据,如文件系统或组织结构。在这里插入图片描述
ttk.LabeledScale()带标签滑块带有内置标签的滑块控件,可自动显示当前值。标签位置可自定义(上 / 下 / 左 / 右)支持格式化显示值 比 tkinter.Scale 更美观、易用在这里插入图片描述
ttk.Scale()滑块功能与 tkinter.Scale类似,外观更现代。在这里插入图片描述
ttk.PanedWindow可调节的窗格布局(可水平或垂直)功能与 tkinter.PanedWindow类似,外观更现代。在这里插入图片描述

4.使用tkinter.ttk模块覆盖tkinter中的控件样式

"""
如何按照一下方式导入tkinter和tkinter.ttk模块,
那么代码中的控件样式会被覆盖为tkk中的控件样式
"""
from tkinter import *
from tkinter.ttk import *


if __name__ == '__main__':
    root = Tk()
	
    
    btn = Button(root, text="这是一个按钮")
    btn.pack()

    root.mainloop()

1-6 tkinter.colorchooser - 颜色选择对话框

colorchooser 模块提供了一个可视化的颜色选择器,用于让用户选择颜色(支持 RGB 或十六进制格式),返回选中的颜色值和确认状态。

1.核心函数:askcolor()

import tkinter as tk
from tkinter import colorchooser

root = tk.Tk()
root.title("颜色选择器示例")

def choose_color():
    # 打开颜色选择对话框
    # 参数:title(标题)、initialcolor(初始颜色)
    color_result = colorchooser.askcolor(
        title="选择背景色",
        initialcolor="#ff0000"  # 初始显示红色
    )
    # 返回值:( (r, g, b), 十六进制颜色 ) 或 (None, None)(取消选择)
    if color_result[1] is not None:  # 用户点击了"确定"
        print(f"RGB值: {color_result[0]}, 十六进制: {color_result[1]}")
        root.configure(bg=color_result[1])  # 应用颜色到窗口

tk.Button(root, text="选择颜色", command=choose_color).pack(pady=20)
root.mainloop()

2.特点

  • 返回值包含 RGB 元组(如 (255, 0, 0))和十六进制字符串(如 "#ff0000")。
  • 支持透明度设置(部分系统支持,返回值会包含 alpha 通道)。

1-7 tkinter.font - 字体管理工具

font 模块用于创建、配置和查询字体,支持动态获取系统可用字体,是处理文本样式的核心工具。

1.常用功能

(1)创建自定义字体

import tkinter as tk
from tkinter import font

root = tk.Tk()

# 创建自定义字体
custom_font = font.Font(
    family="微软雅黑",  # 字体名称
    size=12,           # 字号
    weight="bold",     # 粗细(normal/bold)
    slant="italic",    # 倾斜(roman/italic)
    underline=0,       # 是否下划线(0/1)
    overstrike=0       # 是否删除线(0/1)
)

# 使用默认字体
tk.Label(root, text="默认字体").pack()
# 应用字体到Label控件
tk.Label(root, text="自定义字体示例", font=custom_font).pack(pady=10)

root.mainloop()

在这里插入图片描述

(2)获取系统字体列表
注意:获取的系统字体数量系统有关,不同的系统字体和字体数量可能会不同

import tkinter as tk
from tkinter import font

root = tk.Tk()

# 获取系统可用字体列表
system_fonts = font.families()
print("系统字体数量:", len(system_fonts))
print("前5个字体:", system_fonts[:5])  # 如 ['Arial', 'SimHei', ...]

root.mainloop()

在这里插入图片描述

(3)查询字体属性

import tkinter as tk
from tkinter import font

root = tk.Tk()

# 创建自定义字体
custom_font = font.Font(
    family="微软雅黑",  # 字体名称
    size=12,           # 字号
    weight="bold",     # 粗细(normal/bold)
    slant="italic",    # 倾斜(roman/italic)
    underline=0,       # 是否下划线(0/1)
    overstrike=0       # 是否删除线(0/1)
)

# 应用字体到Label控件
tk.Label(root, text="自定义字体示例", font=custom_font).pack(pady=10)

# 查询字体属性
print("当前字体名称:", custom_font.actual()["family"])  # 获取实际字体名称
print("当前字体大小:", custom_font.actual()["size"])

root.mainloop()

在这里插入图片描述

2.示例代码

import tkinter as tk
from tkinter import font

root = tk.Tk()
root.title("字体管理示例")

# 1. 创建自定义字体
custom_font = font.Font(
    family="微软雅黑",  # 字体名称
    size=12,           # 字号
    weight="bold",     # 粗细(normal/bold)
    slant="italic",    # 倾斜(roman/italic)
    underline=0,       # 是否下划线(0/1)
    overstrike=0       # 是否删除线(0/1)
)

# 2. 获取系统可用字体列表
system_fonts = font.families()
print("系统字体数量:", len(system_fonts))
print("前5个字体:", system_fonts[:5])  # 如 ['Arial', 'SimHei', ...]

# 3. 应用字体到控件
tk.Label(root, text="自定义字体示例", font=custom_font).pack(pady=10)

# 4. 查询字体属性
print("当前字体名称:", custom_font.actual()["family"])  # 获取实际字体名称
print("当前字体大小:", custom_font.actual()["size"])

root.mainloop()

3.技巧

  • 使用 font.actual() 可获取字体的实际属性(解决字体名称映射问题,如系统中没有指定字体时的 fallback)。
  • 通过 font.measure(text) 可计算文本在当前字体下的像素宽度。

1-8 tkinter.simpledialog - 简单输入对话框

simpledialog 提供了快速获取用户输入的对话框,支持整数、浮点数和字符串输入,无需手动创建输入界面。

1.常用函数

函数说明返回值
askstring(title, prompt)输入字符串用户输入的字符串 / None
askinteger(title, prompt)输入整数(自动验证)整数 / None
askfloat(title, prompt)输入浮点数(自动验证)浮点数 / None

2.示例代码

import tkinter as tk
from tkinter import simpledialog

root = tk.Tk()
root.title("简单输入对话框示例")

def get_user_input():
    # 1. 输入字符串
    name = simpledialog.askstring(
        title="输入姓名",
        prompt="请输入你的名字:",
        parent=root  # 绑定到父窗口(确保对话框置顶)
    )
    if name is None:
        print("用户取消输入")
        return

    # 2. 输入整数
    age = simpledialog.askinteger(
        title="输入年龄",
        prompt="请输入你的年龄:",
        minvalue=0,  # 最小值限制
        maxvalue=120  # 最大值限制
    )
    if age is None:
        return

    # 3. 输入浮点数
    height = simpledialog.askfloat(
        title="输入身高",
        prompt="请输入你的身高(米):",
        minvalue=0.5,
        maxvalue=2.5
    )
    if height is None:
        return

    print(f"姓名: {name}, 年龄: {age}, 身高: {height}米")

tk.Button(root, text="打开输入对话框", command=get_user_input).pack(pady=20)
root.mainloop()

3.特点

  • 自动处理输入验证(如 askinteger 会拒绝非整数输入)。
  • 支持 minvalue/maxvalue 限制输入范围。

1-9 tkinter.filedialog - 文件选择对话框

tkinter.filedialog 是 Tkinter 中用于创建文件选择对话框的模块,它提供了多种预定义的对话框,用于打开、保存文件或选择目录。这些对话框具有系统原生外观,使用户体验更加一致。

1.核心功能与对话框类型

filedialog 模块提供了以下主要对话框函数:

函数功能描述
askopenfilename()打开单个文件选择对话框,返回选中的文件路径(字符串)。
askopenfilenames()打开多个文件选择对话框,返回选中的多个文件路径(元组)。
askopenfile()打开单个文件选择对话框,并返回已打开的文件对象(只读模式)。
askopenfiles()打开多个文件选择对话框,并返回已打开的文件对象列表(只读模式)。
asksaveasfilename()打开保存文件对话框,返回用户指定的保存路径(字符串)。
asksaveasfile()打开保存文件对话框,并返回已打开的文件对象(写入模式)。
askdirectory()打开目录选择对话框,返回选中的目录路径(字符串)。

2.常用参数详解

所有对话框函数都支持以下关键参数:

参数说明
title对话框标题(字符串)。
initialdir初始打开的目录路径(字符串),默认是用户主目录。
initialfile初始选中的文件名(仅适用于保存对话框)。
filetypes文件类型过滤器,格式为 [(描述, 扩展名), ...]。例如: [("文本文件", "*.txt"), ("所有文件", "*.*")]
defaultextension保存文件时自动添加的扩展名(如未指定扩展名)。例如: defaultextension=".txt"
parent对话框的父窗口,确保对话框显示在父窗口上方。

3.使用示例

(1) 打开单个文件
import tkinter as tk
from tkinter import filedialog

root = tk.Tk()
root.withdraw()  # 隐藏主窗口

# 打开文件选择对话框
file_path = filedialog.askopenfilename(
    title="选择文件",
    initialdir="/home/user/Documents",  # Linux/Mac 示例路径
    # initialdir="C:/Users/User/Documents",  # Windows 示例路径
    filetypes=[("文本文件", "*.txt"), ("Python 文件", "*.py"), ("所有文件", "*.*")]
)

if file_path:  # 用户点击了"确定"
    print(f"选中的文件: {file_path}")
    # 可以读取文件内容
    with open(file_path, "r") as f:
        content = f.read()
        print(f"文件内容前50个字符: {content[:50]}")
(2)打开多个文件
file_paths = filedialog.askopenfilenames(
    title="选择多个文件",
    filetypes=[("图像文件", "*.jpg;*.png;*.gif"), ("所有文件", "*.*")]
)

if file_paths:
    print(f"选中的文件数量: {len(file_paths)}")
    for path in file_paths:
        print(f"- {path}")
(3)保存文件
save_path = filedialog.asksaveasfilename(
    title="保存文件",
    initialdir="/home/user/Desktop",
    initialfile="new_file",
    defaultextension=".txt",
    filetypes=[("文本文件", "*.txt"), ("PDF 文件", "*.pdf"), ("所有文件", "*.*")]
)

if save_path:
    print(f"保存路径: {save_path}")
    # 可以写入文件内容
    with open(save_path, "w") as f:
        f.write("这是保存的示例内容。")
(4) 选择目录
dir_path = filedialog.askdirectory(
    title="选择目录",
    initialdir="/home/user"
)

if dir_path:
    print(f"选中的目录: {dir_path}")
    # 可以列出目录内容
    import os
    print(f"目录内容: {os.listdir(dir_path)}")

4.进阶技巧

(1)使用文件对象模式
# 使用 askopenfile() 直接获取文件对象
file_obj = filedialog.askopenfile(mode="r")  # 默认只读模式

if file_obj:
    content = file_obj.read()
    print(f"文件内容: {content[:50]}")
    file_obj.close()  # 使用后需要关闭文件
(2) 自定义文件类型过滤器
  • 支持单个扩展名:("文本文件", "*.txt")
  • 支持多个扩展名(用分号分隔):("图像文件", "*.jpg;*.png;*.gif")
  • 支持所有文件:("所有文件", "*.*")
(3)处理取消操作

​ 所有对话框在用户点击 “取消” 时返回 None(或空元组),因此在使用返回值前应先检查是否为 None

5.跨平台注意事项

  • 路径格式:Windows 使用反斜杠 \,而 Linux/Mac 使用正斜杠 /。Tkinter 会自动处理这些差异,但在手动拼接路径时需注意。
  • 文件编码:读取文件时建议指定编码(如 open(file_path, "r", encoding="utf-8")),避免中文等非 ASCII 字符乱码。
  • 目录不存在initialdir 参数指定的目录必须存在,否则对话框可能打开到默认位置。

1-10 tkinter.messagebox - 消息提示对话框

messagebox 用于显示各类提示信息(如警告、错误、询问等),是与用户交互的重要工具。

1.常用函数

函数说明按钮组合返回值(点击的按钮)
showinfo(title=None, message=None, **options)信息提示OK“ok”
showwarning(title=None, message=None, **options)警告提示OK“ok”
showerror(title=None, message=None, **options)错误提示OK“ok”
askquestion(title=None, message=None, **options)询问(是否)Yes/No“yes”/“no”
askyesno(title=None, message=None, **options)确认(是 / 否)Yes/NoTrue/False
askokcancel(title=None, message=None, **options)确认(确定 / 取消)OK/CancelTrue/False
askretrycancel(title=None, message=None, **options)重试(重试 / 取消)Retry/CancelTrue/False

**options支持以下选项:

  • command

    指定当用户关闭对话框时要唤起的函数。 用户关闭对话框所点击的按钮名称将作为参数传入。 此选项仅在 macOS 上可用。

  • default

    指定消息窗口默认按钮的 符号名称 (OK, CANCEL 等等)。 如果未指定此选项,则对话框中的第一个按钮将成为默认。

    # 在 "是/否" 按钮中,默认选中 "否"
    result = messagebox.askyesno(
        title="确认删除",
        message="确定要删除该文件吗?",
        default=messagebox.NO  # 默认选中 "否"
    )
    
  • detail

    为由 message 选项给出的主消息指定一条辅助消息。 消息详情将在主消息之下展示,并且在操作系统支持的情况下,会使用次于主消息的字体。

  • icon

    指定一个要显示的 图标。 如果未指定此选项,则将显示 INFO 图标。

    messagebox.showinfo(
        title="带图标示例",
        message="这是带信息图标的消息框",
        icon=messagebox.INFO  # 显式指定信息图标(默认已包含)
    )
    
  • message

    指定要在此消息框中显示的消息。 默认值为空字符串。

    message="文件保存成功!"
    
  • parent

    将指定的窗口设为该消息框的逻辑上级。 消息框将在其上级窗口之前显示。

    parent=root(root 为主窗口对象)
    
  • title

    指定要作为消息框标题的字符串。 此选项在 macOS 上会被忽略,因为该平台的设计指导禁止在这种对话框中使用标题。

    title="操作提示"
    
  • type

    安排显示一个 预定义的按钮集合

    # 自定义按钮为 "重试" 和 "取消"
    result = messagebox.askquestion(
        title="操作失败",
        message="是否重试?",
        type=messagebox.RETRYCANCEL  # 覆盖默认按钮组合
    )
    

    完整示例:

    import tkinter as tk
    from tkinter import messagebox
    
    root = tk.Tk()
    root.title("messagebox options 示例")
    
    def show_custom_message():
        # 综合配置消息框
        result = messagebox.askquestion(
            title="自定义消息框",          # 标题
            message="是否继续操作?",      # 内容
            parent=root,                 # 父窗口
            icon=messagebox.QUESTION,    # 问号图标
            type=messagebox.YESNOCANCEL, # 按钮组合:是/否/取消
            default=messagebox.CANCEL    # 默认选中 "取消"
        )
        print("用户选择:", result)  # 输出:yes/no/cancel
    
    tk.Button(root, text="显示消息框", command=show_custom_message).pack(pady=50)
    
    root.mainloop()
    

2.示例代码

import tkinter as tk
from tkinter import messagebox

root = tk.Tk()
root.title("消息提示对话框示例")

def show_messages():
    # 1. 信息提示
    messagebox.showinfo(
        title="提示",
        message="操作完成!",
        parent=root
    )

    # 2. 警告提示
    messagebox.showwarning(
        title="警告",
        message="这是一个警告信息!"
    )

    # 3. 错误提示
    messagebox.showerror(
        title="错误",
        message="操作失败,请重试!"
    )

    # 4. 询问(返回 "yes" 或 "no")
    if messagebox.askquestion("询问", "是否保存修改?") == "yes":
        print("用户选择保存")

    # 5. 确认(返回 True/False)
    if messagebox.askyesno("确认", "是否退出程序?"):
        root.destroy()  # 关闭窗口

tk.Button(root, text="显示消息对话框", command=show_messages).pack(pady=20)
root.mainloop()

3.技巧

  • 通过 icon 参数自定义图标(如 icon=messagebox.INFO),但默认已根据函数类型自动设置。
  • 所有对话框会阻塞程序运行,直到用户点击按钮(模态对话框)。

1-11 tkinter.scrolledtext - 带滚动条的文本控件

scrolledtextText 控件的增强版,内置垂直滚动条,适合显示或编辑多行文本(如日志、长文档)。

1.核心功能

  • 自动处理滚动条与文本内容的同步。
  • 支持 Text 控件的所有方法(如插入、删除、获取文本)。

2.示例代码

import tkinter as tk
from tkinter import scrolledtext

root = tk.Tk()
root.title("带滚动条的文本控件示例")
root.geometry("400x300")

# 创建 scrolledtext 控件(宽40字符,高10行)
text_area = scrolledtext.ScrolledText(
    root,
    width=40,
    height=10,
    font=("SimHei", 10),  # 支持中文显示
    wrap=tk.WORD  # 按单词换行(避免截断单词)
)
text_area.pack(padx=10, pady=10, fill=tk.BOTH, expand=True)

# 功能按钮
def insert_text():
    text_area.insert(tk.END, "这是新插入的文本\n")  # 在末尾插入

def clear_text():
    text_area.delete(1.0, tk.END)  # 清空所有内容(1.0 表示第1行第0列)

def get_text():
    content = text_area.get(1.0, tk.END)  # 获取所有内容
    print("文本内容:\n", content)

tk.Button(root, text="插入文本", command=insert_text).pack(side=tk.LEFT, padx=5)
tk.Button(root, text="清空文本", command=clear_text).pack(side=tk.LEFT, padx=5)
tk.Button(root, text="获取文本", command=get_text).pack(side=tk.LEFT, padx=5)

root.mainloop()

3.常用方法(继承自 Text 控件)

  • insert(index, text):在指定位置插入文本(index 格式如 1.0 表示第 1 行第 0 列)。
  • delete(start, end):删除指定范围的文本(tk.END 表示末尾)。
  • get(start, end):获取指定范围的文本。
  • see(index):滚动到指定位置,确保可见。

1-12 常见问题解答

Q1:如何设置窗口图标?
A1:使用 iconbitmap() 方法(Windows/Linux)或 iconphoto() 方法(跨平台):

import tkinter as tk

root = tk.Tk()
root.iconbitmap("path/to/icon.ico")  # Windows
root.iconphoto(True, tk.PhotoImage(file="path/to/icon.png"))  # 跨平台
root.mainloop()

Q2:如何让窗口启动时居中显示?
A2:计算屏幕尺寸并设置窗口位置

import tkinter as tk

root = tk.Tk()
width, height = 400, 300
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x = (screen_width - width) // 2
y = (screen_height - height) // 2
root.geometry(f"{width}x{height}+{x}+{y}")
root.mainloop()

Q3:如何禁用窗口关闭按钮?
A3:覆盖默认关闭行为

import tkinter as tk

root = tk.Tk()
root.protocol("WM_DELETE_WINDOW", lambda: None)  # 禁用关闭按钮
root.mainloop()

Q4:如何去除窗口标题栏?
A4:使用overrideredirect方法去除

import tkinter as tk

root = tk.Tk()
root.overrideredirect(True)  # 隐藏系统标题栏
root.mainloop()

Q5:如何查看tkinter的版本?

import tkinter as tk

if __name__ == '__main__':
    print(tk.TkVersion)
    root = tk.Tk()
    root.mainloop()

第二章 控件的通用属性

2-1 控件通用属性

1. 几何管理属性

属性说明
width控件宽度(像素或字符,取决于控件类型)。
height控件高度(像素或字符,取决于控件类型)。
bg/background背景颜色(如 "red", "#ff0000")。
fg/foreground前景颜色(通常指文本颜色)。
font文本字体(如 ("Arial", 10, "bold"))。
padx控件左右内边距(像素)。
pady控件上下内边距(像素)。

2. 布局与定位属性

属性说明
anchor控件内容的对齐方式(如 tk.CENTER, tk.NW)。
justify多行文本的对齐方式(如 tk.LEFT, tk.CENTER)。
wraplength文本自动换行的宽度(像素)。

3. 状态与交互属性

属性说明
state控件状态(如 tk.NORMAL, tk.DISABLED)。
cursor鼠标悬停时的光标样式(如 "hand2", "arrow")。
takefocus是否可通过 Tab 键聚焦(TrueFalse)。
disabledforeground禁用状态下的文本颜色。

4. 事件绑定属性

属性说明
command控件触发时执行的回调函数(部分控件支持,如 Button)。
textvariable与控件文本绑定的变量(如 tk.StringVar)。

2-2 控件通用方法

1. 基本操作方法

方法说明
pack()使用 Pack 几何管理器放置控件。
grid()使用 Grid 几何管理器放置控件。
place()使用 Place 几何管理器放置控件。
destroy()销毁控件及其所有子控件。
configure(**options)修改控件的属性(如 widget.configure(bg="red"))。也可以使用它来获取控件的参数
config(**options)configure()

2. 状态与属性查询方法

方法说明
cget(option)获取控件的某个属性值(如 widget.cget("bg"))。
winfo_*()获取控件的各种信息,例如: - winfo_width():控件宽度 - winfo_height():控件高度 - winfo_x():控件相对于父容器的 X 坐标 - winfo_y():控件相对于父容器的 Y 坐标
keys()返回控件所有可配置属性的名称列表。

3. 事件处理方法

方法说明
bind(event, handler, add=None)绑定事件处理函数(如 widget.bind("<Button-1>", onclick))。
unbind(event, funcid=None)解除事件绑定。
after(ms, function, *args)在指定毫秒后执行函数。
focus_set()将焦点设置到该控件。

4. 变量绑定方法

方法说明
set(value)设置与控件绑定的变量值(如 StringVar.set("text"))。
get()获取与控件绑定的变量值(如 StringVar.get())。

5. 控件层次结构方法

方法说明
children返回控件的所有子控件(字典形式)。
master返回控件的父容器。
wm_*()窗口管理器方法(仅适用于顶级窗口,如 root.wm_title("标题"))。

2-3 示例-使用共同属性和方法

import tkinter as tk


# 绑定事件
def on_click(event):
    print("点击了标签")
    
root = tk.Tk()

# 创建控件
btn = tk.Button(root, text="按钮", bg="blue", fg="white")
lbl = tk.Label(root, text="标签", font=("Arial", 12))
ent = tk.Entry(root, bg="#f0f0f0")

# 使用共同方法
btn.pack(pady=10)
lbl.pack(pady=5)
ent.pack(pady=5)

# 配置属性
btn.configure(state=tk.DISABLED)
lbl.config(text="新标签文本")

# 查询属性
print(f"按钮背景: {btn.cget('bg')}")
print(f"标签字体: {lbl.cget('font')}")

lbl.bind("<Button-1>", on_click)

# 延迟执行
root.after(2000, lambda: ent.delete(0, tk.END))

root.mainloop()

2-4 注意事项

  1. 属性差异:虽然所有控件都有上述属性,但部分属性对某些控件可能无效(如 widthFrameButton 的解释不同)。
  2. 方法重载:某些方法在不同控件中的行为可能略有不同(如 pack() 在顶级窗口和普通控件中的表现)。
  3. ttk 控件tkinter.ttk 控件的属性名可能略有不同(如 background 变为 style),但核心方法一致。

第三章 Label-标签控件

3-1 控件说明

1.作用

Label 控件是 Tkinter 中用于信息展示的基础核心控件,**其核心作用是在界面上静态或动态地呈现内容**,具体包括:**作为文本展示载体**,用于显示标题、说明文字、数据结果、状态提示等各类文本信息,如表单中的字段名称、程序运行状态说明;**作为图像展示容器**,支持加载并显示图标、Logo、示意图等图像内容;**支持文本与图像的混合展示**,通过配置可灵活设置两者的组合方式(如图文左右排列、上下排列等);还可作为界面布局的辅助元素,通过空文本或固定大小设置来调整元素间距、分隔功能区域;同时,借助变量绑定或属性修改,能够实现内容的动态更新,例如实时显示时间、进度等变化信息,是构建清晰、直观用户界面不可或缺的基础组件。

2.应用场景

  • 表单与数据录入界面:用于显示字段名称(如 “姓名:”、“年龄:”、"地址:"等),为输入框、下拉菜单等交互控件提供说明,帮助用户理解每个输入项的含义,使表单结构清晰易懂。
  • 信息展示区域:可展示各类静态文本信息,如软件的版本号、版权声明、使用说明等;也能动态显示程序运行过程中的状态信息,例如 “正在处理数据…”、“文件已保存”、“连接成功” 等,让用户实时了解程序进展。
  • 图像展示场景:用于显示软件 Logo、功能图标、示意图等图像内容,增强界面的视觉效果和辨识度,比如在应用首页展示品牌 Logo,在功能按钮旁搭配说明图标。
  • 图文混合展示场景:当需要同时呈现文本和图像以丰富信息表达时,Label 能通过配置实现图文组合(如图像在左文本在右、图像在上文本在下等),例如在消息通知中显示提示图标和通知文字,在功能模块标题中搭配相关图标和标题文本。
  • 界面布局辅助:作为布局调整的辅助元素,空文本的 Label 可用于分隔不同功能区域、调整元素间的间距,避免界面元素拥挤;固定尺寸的 Label 还能起到占位作用,确保界面布局的稳定性。
  • 动态信息更新场景:通过绑定变量或直接修改属性,Label 可实时更新内容,适用于显示动态变化的数据,如实时时间、倒计时、进度百分比、传感器采集的实时数据等,让用户直观获取动态信息。

3-2 Label的使用

1.Label创建的语法格式

(1) 使用tkinter创建Label控件的语法格式

注:master是父窗口, options是其他参数

tkLabel = tkinter.Label(master=root, options, ...) 

(2)使用tkinte.ttk创建Label控件的语法格式

注:master是父窗口, options是其他参数

ttkLabel = tkinter.ttk.Label(master=root, options, ...)

2.Label构造方法内的参数说明

(1)tkinter.Label的参数详解
参数名称数据类型参数作用传参示例
masterMisc | None指定 Label 的父组件(容器),如 Tk ()、Frame 等master=root(root 为Tk()实例)
cnfdict[str, Any] | None以字典形式批量设置参数(键为参数名,值为参数值)cnf={‘text’: ‘Hello’, ‘bg’: ‘white’, ‘font’: (‘Arial’, 12)}
activebackgroundstr组件处于 “active” 状态时的背景色(如鼠标悬停时)activebackground=‘lightblue’
activeforegroundstr组件处于 “active” 状态时的前景色(文本 / 图标颜色)activeforeground=‘darkred’
anchorLiteral[“nw”, “n”, “ne”, “w”, “center”, “e”, “sw”, “s”, “se”]文本或图像在 Label 内的对齐方式(方位)anchor=‘center’(居中)、anchor=‘nw’(西北,左上角)
background (bg)str组件的背景色bg=‘white’、background=‘#f0f0f0’(十六进制色值)
bd (border, borderwidth)str | float组件边框宽度(像素)bd=2、borderwidth=‘3’
bitmapstr显示内置位图(如系统预设的错误、警告图标),与 image 互斥bitmap=‘error’(显示错误图标)、bitmap=‘info’
compoundLiteral[“top”, “left”, “center”, “right”, “bottom”, “none”]文本与图像的组合方式(指定图像相对于文本的位置)compound=‘top’(图像在文本上方)、compound=‘left’(图像在文本左侧)
cursorstr | tuple[str] | tuple[str, str] | tuple[str, str, str] | tuple[str, str, str, str]鼠标悬停在组件上时的光标样式(如箭头、手型等)cursor=‘hand2’(手型光标)、cursor=‘arrow’(箭头光标)
disabledforegroundstr组件处于 “disabled” 状态时的前景色(文本 / 图标颜色)disabledforeground=‘gray’
fg (foreground)str组件的前景色(文本 / 图标颜色)fg=‘black’、foreground=‘blue’
fontAny文本的字体设置(可传字体名、大小、样式的元组或 Font 对象)font=(‘SimHei’, 12, ‘bold’)(黑体、12 号、加粗)、font=tkFont.Font (size=14)
heightstr | float组件的高度(单位:字符高度,或像素,取决于平台)height=3(高度为 3 个字符)、height=‘100’(高度 100 像素)
highlightbackgroundstr组件未获得焦点时,聚焦边框的颜色highlightbackground=‘gray’
highlightcolorstr组件获得焦点时,聚焦边框的颜色highlightcolor=‘blue’
highlightthicknessstr | float聚焦边框的厚度(像素),0 表示不显示聚焦边框highlightthickness=1、highlightthickness=‘0’
image_Image | str显示图像(需配合 PhotoImage 等对象),与 bitmap 互斥image=tk.PhotoImage(file=‘logo.png’)
justifyLiteral[“left”, “center”, “right”]多行文本的对齐方式(左对齐、居中、右对齐)justify=‘left’(左对齐)、justify=‘center’(居中)
namestr组件的名称(用于内部标识,通常无需手动设置)name=‘label_1’
padxstr | float组件内部文本 / 图像与左右边框的间距(水平内边距)padx=5(左右各 5 像素)、padx=‘10’
padystr | float组件内部文本 / 图像与上下边框的间距(垂直内边距)pady=3、pady=‘8’
reliefLiteral[“raised”, “sunken”, “flat”, “ridge”, “solid”, “groove”]组件边框的样式(立体效果)relief=‘raised’(凸起)、relief=‘sunken’(凹陷)、relief=‘flat’(扁平)
stateLiteral[“normal”, “active”, “disabled”]组件的状态(正常、激活、禁用)state=‘normal’(正常)、state=‘disabled’(禁用,不可交互)
takefocusint | Literal[“”] | (str) -> bool | None控制组件是否能通过 Tab 键获得焦点(1/True 表示可以,0/False 表示不可)takefocus=True、takefocus=0
textfloat | str组件显示的文本内容text=’ 欢迎使用 '、text=‘123’
textvariableVariable关联的变量(如 StringVar),用于动态更新文本内容var = tk.StringVar (value=’ 动态文本 '); textvariable=var
underlineint指定文本中下划线的位置(索引从 0 开始,-1 表示无下划线)underline=0(下划线第一个字符)、underline=-1(无下划线)
widthstr | float组件的宽度(单位:字符宽度,或像素,取决于平台)width=20(宽度为 20 个字符)、width=‘300’(宽度 300 像素)
wraplengthstr | float文本换行的宽度阈值(超过该宽度时自动换行,单位像素)wraplength=200(超过 200 像素换行)、wraplength=‘150’
(2)ttk.Label参数详解

ttk.Label 是 tkinter.ttk 模块中的标签组件,风格更统一(依赖系统主题),参数比tkinter.Label少,且多数样式通过ttk.Style控制,而非直接通过参数设置。

参数名称参数作用数据类型传参示例
master指定 Label 的父组件(容器),如 Tk ()、ttk.Frame 等Misc | Nonemaster=root(root 为Tk()实例)
cnf以字典形式批量设置参数(键为参数名,值为参数值)dict[str, Any] | Nonecnf={‘text’: 'ttk 标签 ', ‘font’: (‘Arial’, 10)}
text组件显示的文本内容float | strtext='ttk.Label 示例 '、text=‘456’
textvariable关联的变量(如 StringVar),用于动态更新文本内容Variablevar = tk.StringVar (value='ttk 动态文本 '); textvariable=var
image显示图像(需配合 PhotoImage 等对象),与 bitmap 互斥(ttk 中 bitmap 较少用)_Image | strimage=tk.PhotoImage(file=‘icon.png’)
compound文本与图像的组合方式(指定图像相对于文本的位置)Literal[“top”, “left”, “center”, “right”, “bottom”, “none”]compound=‘right’(图像在文本右侧)、compound=‘none’(只显示文本或图像)
anchor文本或图像在 Label 内的对齐方式(方位)Literal[“nw”, “n”, “ne”, “w”, “center”, “e”, “sw”, “s”, “se”]anchor=‘e’(右对齐)、anchor=‘s’(底部对齐)
justify多行文本的对齐方式(左对齐、居中、右对齐)Literal[“left”, “center”, “right”]justify=‘right’(右对齐)、justify=‘center’
wraplength文本换行的宽度阈值(超过该宽度时自动换行,单位像素)str | floatwraplength=180、wraplength=‘250’
font文本的字体设置(可传字体名、大小、样式的元组或 Font 对象)Anyfont=(‘SimHei’, 11)(黑体 11 号)、font=ttk.Font (size=13)
cursor鼠标悬停在组件上时的光标样式str | tuple[str] | tuple[str, str] | tuple[str, str, str] | tuple[str, str, str, str]cursor=‘ibeam’(文本光标)、cursor=‘cross’(十字光标)
state组件的状态(正常、禁用,ttk 中无 “active” 状态)Literal[“normal”, “disabled”]state=‘disabled’(禁用)、state=‘normal’(正常)
takefocus控制组件是否能通过 Tab 键获得焦点int | Literal[“”] | (str) -> bool | Nonetakefocus=False、takefocus=1
padding组件内部的内边距(替代 tkinter.Label 的 padx 和 pady,可统一或分别设置)int | str | tuple[int] | tuple[int, int] | tuple[int, int, int, int]padding=5(四边都是 5 像素)、padding=(2, 4)(上下 2px,左右 4px)
underline指定文本中下划线的位置(索引从 0 开始,-1 表示无下划线)intunderline=2(下划线第三个字符)、underline=-1
width组件的宽度(单位:字符宽度)str | floatwidth=15、width=‘25’
height组件的高度(单位:字符高度)str | floatheight=2、height=‘4’
style关联的样式名称(通过ttk.Style定义,用于统一控制外观)strstyle=‘Custom.TLabel’(关联名为 Custom.TLabel 的样式)
(3)关键区别说明
  • tkinter.Label 直接通过参数(如bgfgrelief)控制样式,灵活性高但风格不统一;
  • ttk.Label 样式主要通过ttk.Style定义,参数更简洁,风格与系统主题一致,推荐用于现代 GUI 开发。

3-3 案例

1.tkinter.Label参数使用示例

(1)master和text参数:设置标签控件的父容器和文本

import tkinter as tk

# 应用程序的主窗口
root = tk.Tk()
# 应用程序的主窗口
root = tk.Tk()
# 设置主窗口标题
root.title("标签控件")
# 设置主窗口的大小
root.geometry("300x300+10+20")

# 创建Label控件并将其命名为label
# master=root表示这个窗口的父容器是root,即就是我的这个控件要放到那个容器里
# text=”需要显示的文本内容“
label = tk.Label(master=root, text="这是一个Label控件") 
# 布局并显示label
label.pack()  # pack()方法可以布局和显示控件在父容器中的位置等

# 运行应用程序
root.mainloop()

在这里插入图片描述

(2)foreground(缩写:fg)参数:设置标签控件的字体颜色

import tkinter as tk

# 应用程序的主窗口
root = tk.Tk()
# 设置主窗口标题
root.title("标签控件")
# 设置主窗口的大小
root.geometry("300x300+10+20")

# 创建Label控件并将其命名为label,并将其字体颜色设置为蓝色
label = tk.Label(master=root, text="这是一个Label控件",
                 foreground="blue")
# 布局并显示label
label.pack()

# 运行应用程序
root.mainloop()

在这里插入图片描述

(3)background(缩写:bg)参数:设置标签控件的背景颜色

import tkinter as tk

# 应用程序的主窗口
root = tk.Tk()
# 设置主窗口标题
root.title("标签控件")
# 设置主窗口的大小
root.geometry("300x300+10+20")

# 创建Label控件并将其命名为label,并将其背景颜色设置为黄色
label = tk.Label(master=root, text="这是一个Label控件",
                 foreground="blue", bg="yellow")
# 布局并显示label
label.pack()

# 运行应用程序
root.mainloop()

在这里插入图片描述

(4)height: 设置标签组件的高度,单位是字符高度

import tkinter as tk

# 应用程序的主窗口
root = tk.Tk()
# 设置主窗口标题
root.title("标签控件")
# 设置主窗口的大小
root.geometry("300x300+10+20")

# 创建Label控件并将其命名为label,并设置其高度为10个字符高度
label = tk.Label(master=root, text="这是一个Label控件",
                 foreground="blue", bg="yellow",
                 height=10)

# 布局并显示label
label.pack()

# 运行应用程序
root.mainloop()

在这里插入图片描述

(5)width: 设置标签组件的宽度,单位是字符宽度

import tkinter as tk

# 应用程序的主窗口
root = tk.Tk()
# 设置主窗口标题
root.title("标签控件")
# 设置主窗口的大小
root.geometry("300x300+10+20")

# 创建Label控件并将其命名为label,并设置其高度为10个字符高度
label = tk.Label(master=root, text="这是一个Label控件",
                 foreground="blue", bg="yellow",
                 height=10, width=30)

# 布局并显示label
label.pack()

# 运行应用程序
root.mainloop()

在这里插入图片描述

(6)anchor: 指定标签文字在标签区域输出的位置,值有nw,n,ne,w,center,e,sw,s,se

在这里插入图片描述

import tkinter as tk

# 应用程序的主窗口
root = tk.Tk()
# 设置主窗口标题
root.title("标签控件")
# 设置主窗口的大小
root.geometry("300x300+10+20")

# 创建Label控件并将其命名为label,并设置标签中的文字位置在nw(西北角的位置)
label = tk.Label(master=root, text="这是一个Label控件",
                 foreground="blue", bg="yellow",
                 height=10, width=30,
                 anchor="nw")

# 布局并显示label
label.pack()

# 运行应用程序
root.mainloop()

在这里插入图片描述

(7)wraplength: 设置标签中的文字在多少宽度后自动换行,单位是像素

import tkinter as tk

# 应用程序的主窗口
root = tk.Tk()
# 设置主窗口标题
root.title("标签控件")
# 设置主窗口的大小
root.geometry("300x300+10+20")

# 创建Label控件并将其命名为label,并设置其文字在110个像素的单位后自动换行
label = tk.Label(master=root, text="这是一个Laebl控件,这是一个Laebl控件",
                 foreground="blue", bg="yellow",
                 height=10, width=30,
                 anchor="nw", wraplength=110)

# 布局并显示label
label.pack()

# 运行应用程序
root.mainloop()

在这里插入图片描述

(8)font: 设置文字字形,参数内容如下

family: 字形,如Times
size: 字体大小,单位像素
weight: 字体的粗细,如bold、normal
slat: 字体倾斜,如italic、roman
underline: 字体是否要有下划线
overstrike: 字体是否要有删除线

注:元组内第一个值和第二个值必须要按参数的顺序传参,不能颠倒顺序,其他的在传参时不受顺序影响,而且参数可以搭配使用

比如:只设置字体和字体大小,font=(“Times”, 20)

import tkinter as tk

# 应用程序的主窗口
root = tk.Tk()
# 设置主窗口标题
root.title("标签控件")
# 设置主窗口的大小
root.geometry("300x300+10+20")


# 创建Label控件并将其命名为label,并设置其font参数
# 注: font参数会影响wraplength参数
label = tk.Label(master=root, text="这是一个Laebl控件,这是一个Laebl控件",
                 foreground="blue", bg="yellow",
                 height=10, width=30,
                 anchor="nw", wraplength=110,
                 font=("Times",   # 字体为Times
                       10,  # 字体大小为10
                       "bold",  # 字体加粗
                       "italic",   # 字体倾斜
                       "underline",   #  字体要有下划线
                       "overstrike"))  # 字体要有删除线

# 布局并显示label
label.pack()

# 运行应用程序
root.mainloop()

在这里插入图片描述

(9)justify: 如果标签中的文字是多行输出,在最后一行输出时可以使用justify参数设置所输出的内容是left/center/right, 默认是居中输出

import pprint
import tkinter as tk

# 应用程序的主窗口
root = tk.Tk()
# 设置主窗口标题
root.title("标签控件")
# 设置主窗口的大小
root.geometry("300x300+10+20")


# 创建Label控件并将其命名为label,并设置其文字内容居左对齐输出
label = tk.Label(master=root, text="这是一个Laebl控件,这是一个Laebl控件",
                 foreground="blue", bg="yellow",
                 height=10, width=30,
                 anchor="nw", wraplength=110,
                 font=("Times", 10,
                       "bold", "italic",
                       "underline", "overstrike"),
                 justify="left")

# 运行应用程序
root.mainloop()

在这里插入图片描述

(10)bitmaps: 位图,只有error/hourglass/info/questhead/question/warning/gray12 /gray25/gray50/gray75

import pprint
import tkinter as tk

# 应用程序的主窗口
root = tk.Tk()
# 设置主窗口标题
root.title("标签控件")
# 设置主窗口的大小
root.geometry("300x300+10+20")

# 创建位图列表
bitmaps = ['error', 'hourglass', 'info', 'questhead',
           'question', 'warning', 'gray12', 'gray25',
           'gray50', 'gray75']
# 使用for循环在创建标签的同时,设置bitmap参数
for bitmap in bitmaps:
    tk.Label(root, bitmap=bitmap).pack()

# 运行应用程序
root.mainloop()

在这里插入图片描述

(11)compound: 当图像与文字共存时使用它定义文字与图像的位置,值如下
left: 图像在左
right: 图像在右
top: 图像在上
bottom: 图像在下
center: 文字覆盖在图像上方

import tkinter as tk

# 应用程序的主窗口
root = tk.Tk()
# 设置主窗口标题
root.title("标签控件")
# 设置主窗口的大小
root.geometry("300x300+10+20")

# 位图图片-文本字典
bitmaps_text_dict = {'error': '这是一个error位图',
                     'gray12': '这是一个gray12位图',
                     'gray25': '这是一个gray25位图',
                     'gray50': '这是一个gray50位图',
                     'gray75': '这是一个gray75位图',
                     'hourglass': '这是一个hourglass位图',
                     'info': '这是一个info位图',
                     'questhead': '这是一个questhead位图',
                     'question': '这是一个question位图',
                     'warning': '这是一个warning位图'}


# 遍历位图图片-文本字典的同时创建标签控件,设置标签控件的位图图片和文本文字,
# 设置位图图片在标签控件中居左,文本在标签控件中居右
for key, value in bitmaps_text_dict.items():
    tk.Label(root, bitmap=key, text=value,
             compound="left").pack()

# 运行应用程序
root.mainloop()

在这里插入图片描述

(12)relief: 设置组件的边框样式和立体效果,值如下
flat: 无边框,组件与背景完全平齐(默认值)
raised: 边框凸起,形成立体的浮出效果
sunken: 边框凹陷,形成嵌入效果
ridge: 边框呈脊状凸起,边缘有明显的立体感,常用于Frame组件
groove: 边框呈凹槽状凹陷,与ridge相反,形成内凹的立体槽效果
solid: 显示单一线条边框,宽度由borderwidth决定,无立体效果。

import tkinter as tk

# 应用程序的主窗口
root = tk.Tk()
# 设置主窗口标题
root.title("标签控件")
# 设置主窗口的大小
root.geometry("300x300+10+20")


reliefs: list[str] = ["raised", "sunken", "flat", "ridge", "solid", "groove"]

for i in range(len(reliefs)):
    tk.Label(root, text=reliefs[i],
             bg="yellow", relief=reliefs[i]).pack(pady=3)
# 运行应用程序
root.mainloop()

在这里插入图片描述

(13)padx: 设置文字左右边界与标签的区间的x轴间距

import tkinter as tk

# 应用程序的主窗口
root = tk.Tk()
# 设置主窗口标题
root.title("标签控件")
# 设置主窗口的大小
root.geometry("300x300+10+20")

# 创建标签控件
label1 = tk.Label(root, text="Flat",
                  bg="yellow")
# 布局并显示标签控件
label1.pack()

# 创建标签控件,并设置其padx=10
label2 = tk.Label(root, text="Flat",
                  bg="yellow",
                  padx=10)
# 布局并显示标签控件
label2.pack()

# 运行应用程序
root.mainloop()

在这里插入图片描述

(14)pady: 设置文字左右边界与标签的区间的y轴间距

import tkinter as tk

# 应用程序的主窗口
root = tk.Tk()
# 设置主窗口标题
root.title("标签控件")
# 设置主窗口的大小
root.geometry("300x300+10+20")

# 创建标签控件
label1 = tk.Label(root, text="Flat",
                  bg="yellow")
# 布局并显示标签控件,pack方法也可以设置参数,而这些参数可以影响控件在父容器中的位置布局,详解见第四章
label1.pack(pady=(0, 5))

# 创建标签控件,并设置其pady=10
label2 = tk.Label(root, text="Flat",
                  bg="yellow",
                  pady=10)
# 布局并显示标签控件
label2.pack()

# 运行应用程序
root.mainloop()

在这里插入图片描述

(15)image: 设置图像,需要借助PhotoImage显示PGM, PPM, GIF, PNG格式图像,显示jpg格式图像需要借助PIL的Image和ImageTK

注:tkinter.PhotoImage() 适合处理简单的 PGM, PPM, GIF, PNG,GIF 图像,支持基本的缩放和像素操作。对于复杂场景(如多格式支持、高质量缩放),建议结合 Pillow 库(第三方库)使用。注意保持对象引用和内存管理,避免图像显示异常。

import tkinter as tk
from PIL import Image, ImageTk

# 应用程序的主窗口
root = tk.Tk()
# 设置主窗口标题
root.title("标签控件")
# 设置主窗口的大小
root.geometry("300x300+10+20")

# 创建可以显示图片的标签控件
#方法1
# 使用tk.PhotoImage方法加载图片
image1 = tk.PhotoImage(file="../assets/chapter1/1-6.jpg")
# 创建标签控件,并设置image参数,显示图片
label1 = tk.Label(root, image=image1)
# 保持引用,防止被垃圾回收
label1.image = image1
# 布局并显示标签控件
label1.pack(pady=(0, 5))

# 方法2
# 使用PIL中的Image.open方法加载图片
image2 = Image.open("../assets/chapter1/1-6.jpg")
# 使用PIL中的ImageTk.PhotoImage方法将加载的图片转换长tkinter可以使用的PhotoImage 对象
photo2 = ImageTk.PhotoImage(image2)
# 创建标签控件,并设置image参数,显示图片
label2 = tk.Label(root, image=photo2)
# 保持引用,防止被垃圾回收
label2.image = image2
# 布局并显示标签控件
label2.pack()

# 运行应用程序
root.mainloop()

在这里插入图片描述

(16)cursor: 设置光标在组件上的形状,如何不设置,默认延用父容器上的光标形状

光标形状及其值:

在这里插入图片描述
在这里插入图片描述

import tkinter as tk
from PIL import Image, ImageTk

# 应用程序的主窗口
root = tk.Tk()
# 设置主窗口标题
root.title("标签控件")
# 设置主窗口的大小
root.geometry("300x300+10+20")

# 创建标签控件,并设置cursor参数,当鼠标移动到标签控件上时,鼠标会变成船的形状
label1 = tk.Label(root, text="1111111",
                  background="yellow",
                  cursor="boat")
label1.pack()

# 运行应用程序
root.mainloop()

2.ttk.Label参数使用示例

注:在这个示例中重点是讲styel参数如何使用,其他参数的使用和tkinter.Label中的参数用法一样

(1)style参数:设置控件的样式

使用步骤

步骤一:初始化Style实例

步骤二:使用Style示例的configure方法设置样式

步骤三: 设置标签控件的style样式,使其关联上自定义的标签样式

configure方法语法:style.configure(样式名, **属性)

ttk 控件的样式有固定命名规则,比如配置标签写法是style.configure(“TLabel”, **属性)

import tkinter as tk
from tkinter import ttk

# 应用程序的主窗口
root = tk.Tk()
# 设置主窗口标题
root.title("标签控件")
# 设置主窗口的大小
root.geometry("300x300+10+20")

# 创建Style实例(全局唯一,通常只需创建一个)
style = ttk.Style()
# 修改ttk.Label的默认样式(TLabel)
style.configure("TLabel",
                background="yellow",
                relief="solid")
# 创建标签并设置style参数,使其与自己自定义的样式关联
label1 = ttk.Label(root, text="这是一个ttk.Label控件",
                   style="TLabel")
label1.pack()

# 运行应用程序
root.mainloop()

在这里插入图片描述

第四章 控件的布局管理及显示

4-1 布局管理说明

​ 在 tkinter 中,pack ()、grid () 和 place () 是三种常用的几何管理方法,用于控制组件在父容器中的布局位置。pack () 方法通过 “打包” 的方式将组件按添加顺序排列,可通过 side 参数指定排列方向(如左、右、上、下),并自动调整组件大小以适应容器,适合简单的线性布局;grid () 方法采用网格(行列)结构布局组件,通过 row 和 column 参数指定组件所在的单元格,支持跨行列(rowspan、columnspan)和单元格内对齐(sticky),适用于规则的表格状布局;place () 方法则允许通过 x、y 坐标精确指定组件在容器中的位置,也可通过 width 和 height 设置组件大小,适合需要精确定位的场景,但灵活性较低,布局调整时需手动修改坐标参数。

​ 若无特殊需求,建立使用pack()和grid()布局管理控件在容器中的位置和显示

4-2 使用pack方法布局

1.pack方法参数

参数名称说明
side可以垂直或水平配置组件,参数取值如下
TOP: 默认值,由上往下排列
BOTTOM: 由下往上排列
LEFT: 由左往右排列
RIGHT: 由右往左排列
fill设置控件填满所分配的容器区间,参数值如下
fill=“x”: 表示控件可以填满所分配空间的x轴不留白
fill=“y”: 表示控件可以填满所分配空间的y轴不留白
fill=“both”: 表示控件可以填满所分配空间的x轴和y轴
fill=“none”: 表示保持原大小
如果所分配容器区域已经填满,fill参数将不会有任何作用
padx/pady设置指定组件边界与容器的水平或垂直间距或者是组件之间的水平或垂直间距,
padx/pady的参数格式有两种,一种是单值,一种是元组。
pady用于设置垂直方向的间距,具体参数格式如下:
(1)单值:pady=10
表示控件上方和下方的间距相等,均为10像素
(2)元组:pady=(上间距,下间距)
如pady=(0, 10)表示上方间距0像素,下方间距10像素,实现上下不对称
的间距效果
padx用于设置水平方向的间距,具体参数格式如下:
(1)单值:padx=5
表示控件左方和右方的间距相等,均为5像素
(2)元组:padx=(左间距,右间距)
如padx=(2, 8)表示左间距2像素,右间距8像素
ipadx/ipady设置标签文字与标签容器的x轴或y轴间距
anchor设置标签组件在容器中的位置,可取的值有"nw", “n”, “ne”, “w”, “center”, “e”, “sw”, “s”, “se”
expand可以设置组件是否填满额外的父容器空间,默认为False表示不填满额外空间,True表示填满额外空间,而何时需要填满父容器的额外空间取决于你的布局要求以及side和fill参数

注:

  • pack是tkinter中的一个类别,它还提供了下列方法:
    slaves(): 传回所有组件对象
    info(): 传回pack选项对应的值
    forget(): 隐藏组件,可以用pack()复原显示
    location(): 传回此点是否在单元格,如果是,传回坐标,如果不是传回(-1,-1)
    size(): 传回组件大小
    propagate(boolean): 参数是True表示父窗口大小由子控件决定,默认为True

2.案例

(1)side参数

  • side=“top”,默认值,当布局需求是从上到下依次布局时使用,也可以不写side=“top”

    import tkinter as tk
    from tkinter import ttk
    
    # 应用程序的主窗口
    root = tk.Tk()
    root.title("pack布局显示")
    root.geometry("300x100")
    
    """
    创建三个标签控件,当控件布局为pack(side="top")
    三个控件会按照布局的顺序从上到下一次布局显示。
    当你调整了布局时的顺序,控件的位置也会发生变化,
    比如已经创建了三个标签控件,但我先布局控件的顺序是
    label2.pack(side=top)
    label1.pack(side=top)
    label3.pack(side=top)
    那么界面会显示出label2控件在第一个,label1控件在第二个
    label3控件在第三个
    """
    label1 = ttk.Label(root, text="第一个标签控件",
                       background="yellow")
    label1.pack(side="top")
    
    
    label2 = ttk.Label(root, text="第二个标签控件",
                       background="purple")
    label2.pack(side="top")
    
    label3 = ttk.Label(root, text="第三个标签控件",
                       background="blue")
    label3.pack(side="top")
    
    
    # 运行应用程序
    root.mainloop()
    
    

    在这里插入图片描述

  • side=“bottom”,从下到上开始布局,刚好与side="top"相反

    import tkinter as tk
    from tkinter import ttk
    
    # 应用程序的主窗口
    root = tk.Tk()
    root.title("pack布局显示")
    root.geometry("300x100")
    
    label1 = ttk.Label(root, text="第一个标签控件",
                       background="yellow")
    label1.pack(side="bottom")
    
    label2 = ttk.Label(root, text="第二个标签控件",
                       background="purple")
    label2.pack(side="bottom")
    
    label3 = ttk.Label(root, text="第三个标签控件",
                       background="blue")
    label3.pack(side="bottom")
    
    # 运行应用程序
    root.mainloop()
    

    在这里插入图片描述

  • side=“left”, 由左往右排列

    import tkinter as tk
    from tkinter import ttk
    
    # 应用程序的主窗口
    root = tk.Tk()
    root.title("pack布局显示")
    root.geometry("300x100")
    
    label1 = ttk.Label(root, text="第一个标签控件",
                       background="yellow")
    label1.pack(side="left")
    
    label2 = ttk.Label(root, text="第二个标签控件",
                       background="purple")
    label2.pack(side="left")
    
    label3 = ttk.Label(root, text="第三个标签控件",
                       background="blue")
    label3.pack(side="left")
    
    # 运行应用程序
    root.mainloop()
    
    

    在这里插入图片描述

  • side=“right”, 由右往左排列

    import tkinter as tk
    from tkinter import ttk
    
    # 应用程序的主窗口
    root = tk.Tk()
    root.title("pack布局显示")
    root.geometry("300x100")
    
    label1 = ttk.Label(root, text="第一个标签控件",
                       background="yellow")
    label1.pack(side="right")
    
    label2 = ttk.Label(root, text="第二个标签控件",
                       background="purple")
    label2.pack(side="right")
    
    label3 = ttk.Label(root, text="第三个标签控件",
                       background="blue")
    label3.pack(side="right")
    
    # 运行应用程序
    root.mainloop()
    

    在这里插入图片描述

(2)fill参数

注:当pack是自上而下或自下而上布局时,fill="y"是不起作用的,需要搭配expand=1使用;同理当布局时自左向右或自右向左布局,fill="x"是没有用的,也需要搭配expand=1使用。简单记法:上下布局,fill="y"填不满,左右布局,fill="x"填不满

  • fill=“x”,表示控件可以填满所分配空间的x轴不留白

    root = tk.Tk()
    root.title("pack布局显示")
    root.geometry("300x100")
    
    # 控件自上向下布局,label1的X轴不填满,label2的x轴填满
    label1 = ttk.Label(root, text="第一个标签控件",
                       background="yellow")
    label1.pack()
    
    label2 = ttk.Label(root, text="第二个标签控件",
                       background="purple")
    label2.pack(fill="x")
    
    
    # 运行应用程序
    root.mainloop()
    

    在这里插入图片描述

  • fill=“y”,表示控件可以填满所分配空间的y轴不留白

    import tkinter as tk
    from tkinter import ttk
    
    # 应用程序的主窗口
    root = tk.Tk()
    root.title("pack布局显示")
    root.geometry("300x100")
    
    # 控件自左向右布局,label1的y轴不填满,label2的y轴填满
    label1 = ttk.Label(root, text="第一个标签控件",
                       background="yellow")
    label1.pack(side="left")
    
    label2 = ttk.Label(root, text="第二个标签控件",
                       background="purple")
    label2.pack(side="left", fill="y")
    

    在这里插入图片描述

  • fill=“both”,表示控件可以填满所分配空间的x轴和y轴

    import tkinter as tk
    from tkinter import ttk
    
    # 应用程序的主窗口
    root = tk.Tk()
    root.title("pack布局显示")
    root.geometry("300x100")
    
    # 控件自左向右布局,label1的x和y轴不填满,label2的x和y轴都填满
    label1 = ttk.Label(root, text="第一个标签控件",
                       background="yellow")
    label1.pack(side="left")
    
    label2 = ttk.Label(root, text="第二个标签控件",
                       background="purple")
    label2.pack(side="left", fill="both", expand=1)
    
    
    # 运行应用程序
    root.mainloop()
    

    在这里插入图片描述

  • fill=“none”,表示保持原大小

  • 小技巧

    可能我们有时想要左右布局没有明确大小的控件,想要让控件即可以填满容器的x和y轴,还可以让几个控件在容器其等比例的填满,这中既要又要的想法就要请出三个参数,搭配使用,他们哥仨是side、fill、expand

    import tkinter as tk
    from tkinter import ttk
    
    # 应用程序的主窗口
    root = tk.Tk()
    root.title("pack布局显示")
    root.geometry("300x100")
    
    label1 = ttk.Label(root, text="第一个标签控件",
                       background="yellow")
    label1.pack(side="left", fill="both", expand=1)
    
    label2 = ttk.Label(root, text="第二个标签控件",
                       background="purple")
    label2.pack(side="left", fill="both", expand=1)
    
    # 运行应用程序
    root.mainloop()
    

在这里插入图片描述

(3)padx/pady参数

import tkinter as tk
from tkinter import ttk

if __name__ == '__main__':
    # 应用程序的主窗口
    root = tk.Tk()
    root.title("pack布局显示")
    root.geometry("300x100")
	
    label1 = ttk.Label(root, text="第一个标签控件",
                       background="yellow")
    # 标签控件1设置水平间距(左右间距都是20px)为20px
    label1.pack(side="left", fill="both", expand=1,
                padx=20)

    label2 = ttk.Label(root, text="第二个标签控件",
                       background="purple")
    # 标签控件2设置垂直间距(上下间距都是20px)为20px
    label2.pack(side="left", fill="both", expand=1,
                pady=20)
    
    root.mainloop()

在这里插入图片描述

(4)ipadx/ipady参数

注:pack方法中的ipadx/ipady可能会受pack方法中的fill、expand或其他参数以及控件文本的默认对齐方式干扰,从而影响显示效果,因此在设置ipadx和ipady时,要考虑ipadx和ipady是否会受影响。

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
root.title("ipadx 实际效果")
root.geometry("400x100")


label1 = ttk.Label(
    root,
    text="有设置ipadx",
    background="yellow",
    relief="solid",  # 显示边框
    anchor="center"  # 关键:文本居中
)
label1.pack(side="left",
            padx=20,
            ipadx=20)

# 添加边框,直观显示控件范围
label2 = ttk.Label(
    root,
    text="没有设置ipadx",
    background="yellow",
    relief="solid",  # 显示边框
)
label2.pack(side="left",
            padx=20)
root.mainloop()

在这里插入图片描述

(5)anchor参数

注:在 Tkinter 中,pack() 方法的 anchor 参数通常需要配合 side 参数使用,否则可能无法达到预期的布局效果。这是因为 anchor 的作用依赖于 side 所定义的 “排列方向” 和控件的 “可用空间”。

布局空间:

在这里插入图片描述

import tkinter as tk

root = tk.Tk()
root.geometry("400x100")

# anchor可取值列表
anchor_string: list = ["nw", "n", "ne", "w", "center", "e", "sw", "s", "se"]

# 使用循环生成和布局组件
for i in range(len(anchor_string)):
    tk.Button(root,
              text=f"{anchor_string[i]}").pack(anchor=anchor_string[i])

root.mainloop()

在这里插入图片描述

(6)expand参数

注:expand参数一般配合fill参数使用

import tkinter as tk


root = tk.Tk()
root.geometry("300x300")

button1 = tk.Button(root, text="没有设置expand的参数")
button1.pack()

button2 = tk.Button(root, text="设置了expand的参数")
button2.pack(pady=(10, 0),
             fill="both",
             expand=True)

root.mainloop()

在这里插入图片描述

4-2 使用grip方法布局

1.grip方法参数

参数名称说明
row和column调整row和column的值,可以调整组件在grid布局中的位置
columnspan设置组件在column方向的合并数量
rowspan设置组件在row方向的合并数量
padx/pady设置指定组件边界与容器的水平或垂直间距或者是组件之间的水平或垂直间距
sticky功能与 fill 基本一致,而 sticky + grid_columnconfigure/grid_rowconfigure(设置 weight 的组合效果,完全等同于 pack() 中的 fill + expand 组合,但只能设定N/S/W/E,即上/下/左/右对齐,sticky组合的参数值如下
sticky=N+S: 可以拉长高度让组件在顶端和底端对齐
sticky=W+E: 可以拉长宽度让组件在左边和右边对齐
sticky=N+S+E: 可以拉长高度让组件在顶端和底端对齐,同时切齐右边
sticky=N+S+W: 可以拉长高度让组件在顶端和底端对齐,同时切齐左边
sticky=N+S+W+E: 可以拉长高度让组件在顶端和底端对齐,同时切齐右边

2.案例

(1)row和column参数

注:row和column的参数值是从0开始算起的,比如放置某个控件在网格中的第1行第1列,那么此时row=0,column=0

import tkinter as tk

root = tk.Tk()

button1 = tk.Button(root, text="button1")
# 网格布局,让button1放置在网格的第1行第1列
button1.grid(row=0, column=0)

button2 = tk.Button(root, text="buttoun2")
# 网格布局,让button1放置在网格的第1行第2列
button2.grid(row=0, column=1)

button3 = tk.Button(root, text="buttoun3")
# 网格布局,让button1放置在网格的第1行第3列
button3.grid(row=0, column=2)

root.mainloop()

在这里插入图片描述

(2)columnspan参数

:在使用columnspan参数跨列合并是要注意避免空白列,因为columnspan 合并的是连续的列索引,所以要确保列索引连续且合理使用,同时通过配置列权重和尺寸来控制布局

示例:

1.当列索引不连续时,button4控件合并三列
行0:[button1(0)] [button2(1)] [空白列(2)] [button3(3)]
行1:[button4(0-2)]            [空白列(2)] [button3(3)]
# 当需要合并3列时,button4只到column=2,与button3(column=3)之间有空白

2.当列索引连续时,button4控件合并三列
行0:[button1(0)] [button2(1)] [button3(2)]
行1:[button4(0-2)(横跨3列,与button3对齐)]

总结:避免空白列的核心原则

  1. 列索引连续:从 0 开始依次使用,不跳过任何索引(如 0→1→2 而非 0→1→3)。
  2. 用间距替代空白列:通过 padxgrid_columnconfigure 控制列间距,而非跳过索引。
  3. 填充控件空白:用 sticky 参数让控件拉伸填充列空间,消除视觉空白。
  4. 精确使用 columnspan:合并的列数不超过实际存在的列数。
import tkinter as tk

root = tk.Tk()

# 网格布局,让button1放置在网格的第1行第1列
button1 = tk.Button(root, text="button1")
button1.grid(row=0, column=0)

# 网格布局,让button1放置在网格的第1行第2列
button2 = tk.Button(root, text="button2")
button2.grid(row=0, column=1)

# 网格布局,让button1放置在网格的第1行第3列
button3 = tk.Button(root, text="button3")
button3.grid(row=0, column=2)

# 网格布局,让button1放置在网格的第2行第1列,并设置sticky=tk.W + tk.E,可以拉长宽度让组件在左边和右边对齐
button4 = tk.Button(root, text="button4")
button4.grid(row=1, column=0, columnspan=3,
             sticky=tk.W + tk.E)

root.mainloop()

在这里插入图片描述

(3)rowspan参数

注:与columnspan相同

import tkinter as tk

root = tk.Tk()

# 创建第1行的按钮控件
button1 = tk.Button(root, text="button1")
# 设置rowspan=2,使其button1控件横跨2行,并设置sticky= tk.N + tk.S,使其填满合并后的其它剩余空间
button1.grid(row=0, column=0,
             rowspan=2,
             sticky=tk.N + tk.S)

button2 = tk.Button(root, text="button2")
button2.grid(row=0, column=1)

button3 = tk.Button(root, text="button3")
button3.grid(row=0, column=2)

# 创建第2行的按钮控件
button4 = tk.Button(root, text="button4")
button4.grid(row=1, column=1)

button5 = tk.Button(root, text="button5")
button5.grid(row=1, column=2)

root.mainloop()

在这里插入图片描述

(4)padx/pady参数

:与pack的padx和padx的用法一致

import tkinter as tk

root = tk.Tk()

# 设置button1的padx=3, pady=3
button1 = tk.Button(root, text="button1")
button1.grid(row=0, column=0,
             rowspan=2,
             sticky=tk.N + tk.S,
             padx=3,
             pady=3)

button2 = tk.Button(root, text="button2")
button2.grid(row=0, column=1)

button3 = tk.Button(root, text="button3")
button3.grid(row=0, column=2)


button4 = tk.Button(root, text="button4")
button4.grid(row=1, column=1)

button5 = tk.Button(root, text="button5")
button5.grid(row=1, column=2)

root.mainloop()

在这里插入图片描述

(5)sticky参数

注:grid的sticky与pack的fill参数作用类似,grid的stick+root.grid_columnconfigure()/root.grid_rowconfigure()或者root.rowconfigure()/root.columnconfigure()与pack的fill+expand作用类型

pack() 布局grid() 布局效果说明
fill=tk.Xsticky=tk.EW(东 - 西,即水平方向)控件在水平方向填充分配的空间
fill=tk.Ysticky=tk.NS(北 - 南,即垂直方向)控件在垂直方向填充分配的空间
fill=tk.BOTHsticky=tk.NSEW(四个方向)控件在水平和垂直方向填充分配的空间
expand=Truegrid_columnconfigure(列, weight=1) grid_rowconfigure(行, weight=1)让列 / 行扩大以占据父容器的额外空闲空间
fill=tk.BOTH + expand=Truesticky=tk.NSEW + 列/行 weight=1控件填满整个父容器(最常用的 “全屏” 效果)
import tkinter as tk

root = tk.Tk()

button1 = tk.Button(root, text="button1",
                    relief="solid")
button1.grid(row=0, column=0,
             rowspan=2,
             sticky=tk.NSEW)

root.grid_columnconfigure(0, weight=1)
root.grid_rowconfigure(0, weight=1)

root.mainloop()

在这里插入图片描述

4-3 使用place方法布局

注:place是使用直接指定的方式将组件放到容器中的方法

1.place方法参数

参数名称说明
x/y直接设定窗口组件的左上方位置,单位是像素。窗口显示区的
左上角是(x=0,y=0),x是向右递增,y是向下递增,同时使用
这种方法,窗口将不会自动重设大小而是使用默认的大小显示
width/height设置组件的实体大小
relx/rely与relwidth/relheightrelx/rely可以设置相对于
父窗口的位置,relwidth/relheight设置相对大小(相对于父窗口而言)。这个相对
位置与相对大小是相对于父窗口而言,其值为0.0-1.0
anchor控件的锚点(即 x/y 或 relx/rely 对应的位置),默认值为 nw(左上角)。
可选值:n(北)、s(南)、e(东)、w(西)、center(中心)等。
bordermode边界模式,默认inside(不包含父容器边框),outside 则包含边框

2.案例

(1)x/y参数

import tkinter as tk
from tkinter import ttk

if __name__ == '__main__':
    root = tk.Tk()
    root.geometry("300x300+300+300")
    
    # 将控件button1放置到root窗口的x=30,y=30的位置
    button1 = ttk.Button(root, text="button1")
    button1.place(x=30, y=30)
	
    # 将控件button2放置到root窗口的x=120,y=30的位置
    button2 = ttk.Button(root, text="button2")
    button2.place(x=120, y=30)

    root.mainloop()

在这里插入图片描述

(2)width/height参数

import tkinter as tk
from tkinter import ttk

if __name__ == '__main__':
    root = tk.Tk()
    root.geometry("300x300+300+300")
    button1 = ttk.Button(root, text="button1")
    button1.place(x=30, y=30)
	
    button2 = ttk.Button(root, text="button2")
    # 
    button2.place(x=120, y=30,
                  height=60)

    root.mainloop()

在这里插入图片描述

(3)relx/rely与relwidth/relheight参数

注:

  • relx/rely/relwidth/relheight以父容器的尺寸为基准,按比例计算控件的位置和大小,实现响应式布局(父容器尺寸变化时,控件会按比例自动调整)。
  • Tkinter 中 place() 默认以控件的左上角为基准点(anchor="nw"),如需居中需显式设置 anchor="center"
import tkinter as tk
from tkinter import ttk

if __name__ == '__main__':
    root = tk.Tk()
    root.geometry("400x300")  # 父容器尺寸:宽400,高300

    # 控件相对于父容器的坐标为x=父窗口宽度的50%,y=父窗口高度的50%
    button1 = ttk.Button(root, text="button1")
    button1.place(
        relx=0.5,    # x方向居中(父容器宽度的50%)
        rely=0.5,    # y方向居中(父容器高度的50%)
        relwidth=0.3,  # 宽度为父容器的30%(400*0.3=120)
        relheight=0.3,  # 高度为父容器的30%(300*0.3=90)
    )

    root.mainloop()

在这里插入图片描述

(4)anchor参数

import tkinter as tk

if __name__ == '__main__':
	root = tk.Tk()
	root.geometry("400x300")  # 父容器尺寸:宽400,高300
 	# 控件相对于父容器的坐标为x=父窗口宽度的50%,y=父窗口高度的50%
    button1 = ttk.Button(root, text="button1")
    button1.place(
        relx=0.5,    # x方向居中(父容器宽度的30%)
        rely=0.5,    # y方向居中(父容器高度的30%)
        relwidth=0.3,  # 宽度为父容器的30%(400*0.3=120)
        relheight=0.3,  # 高度为父容器的30%(300*0.3=90)
        anchor=tk.CENTER # 以控件中心为基准点
    )
	root.mainloop()

在这里插入图片描述

(5)bordermode参数

bordermode 是 Tkinter 中 place() 布局的一个参数,用于控制控件定位和尺寸计算时是否包含边框(border)。它主要影响 x/y(绝对坐标)和 relx/rely(相对坐标)的计算基准,可选值为 "inside"(默认)和 "outside"

import tkinter as tk
from tkinter import ttk

if __name__ == '__main__':
    root = tk.Tk()
    root.title("bordermode 参数示例")
    root.geometry("400x300")

    # 创建一个带边框的父容器(边框宽度为10px,突出显示边框影响)
    parent_frame = ttk.Frame(
        root,
        relief="solid",  # 实线边框
        borderwidth=10   # 边框宽度10px
    )
    parent_frame.pack(fill="both", expand=True, padx=20, pady=20)

    # 1. bordermode="inside"(默认):坐标计算不包含父容器的边框
    # 控件定位以父容器的内边距(边框内侧)为基准
    inside_btn = ttk.Button(
        parent_frame,
        text="bordermode='inside'"
    )
    inside_btn.place(
        x=0, y=0,  # 理论上贴左上角
        bordermode="inside"  # 默认值,可省略
    )

    # 2. bordermode="outside":坐标计算包含父容器的边框
    # 控件定位以父容器的外边距(边框外侧)为基准
    outside_btn = ttk.Button(
        parent_frame,
        text="bordermode='outside'"
    )
    outside_btn.place(
        x=0, y=50,  # 同样设置x=0, y=50
        bordermode="outside"
    )

    # 3. 对比相对布局的差异(relx=0 时的位置)
    inside_rel_btn = ttk.Button(
        parent_frame,
        text="relx=0 (inside)"
    )
    inside_rel_btn.place(
        relx=0, rely=0.5,  # 相对x=0
        bordermode="inside"
    )

    outside_rel_btn = ttk.Button(
        parent_frame,
        text="relx=0 (outside)"
    )
    outside_rel_btn.place(
        relx=0, rely=0.65,  # 相对x=0
        bordermode="outside"
    )

    root.mainloop()

在这里插入图片描述

代码说明:

  1. 父容器设置:创建了一个带 10px 边框的 parent_frame,用于突出显示边框对定位的影响。
  2. bordermode="inside"(默认)
    • 控件的 x=0/y=0 以父容器边框内侧为基准(忽略边框宽度)。
    • 示例中 inside_btn 会紧贴父容器的内边缘(边框内侧)。
  3. bordermode="outside"
    • 控件的 x=0/y=0 以父容器边框外侧为基准(包含边框宽度)。
    • 示例中 outside_btn 会向左偏移(超出父容器的内边缘),因为它以边框外侧为起点计算。

直观效果:

  • inside 模式下,控件不会超出父容器的边框内侧,定位更 “安全”(适合大多数场景)。
  • outside 模式下,控件可能会部分或完全超出父容器的边框(适合需要控件 “挂在” 容器边缘外侧的场景)。
  • 这个参数在父容器有明显边框(borderwidth > 0)时效果差异最明显,默认使用 inside 即可满足大多数布局需求。

第五章 Button-按钮控件

5-1 控件说明

1.作用

​ Button(按钮)是 Tkinter 中最基础的交互控件之一,主要用于响应用户的点击操作,触发预设的事件处理函数(如执行命令、切换状态、打开新窗口等)。它是用户与程序交互的核心入口,通过可视化的按钮元素,将程序功能以直观的方式呈现给用户。

2.应用场景

  • 执行核心命令:如 “提交”“保存”“删除”“退出” 等操作(例:表单提交按钮、文件保存按钮)。
  • 状态切换:如 “开始 / 暂停”“显示 / 隐藏” 等互斥功能(例:播放器的播放 / 暂停按钮)。
  • 导航跳转:如 “下一步”“返回”“打开设置” 等页面或功能切换(例:向导类程序的步骤跳转按钮)。
  • 辅助功能:如 “帮助”“重置”“清空” 等辅助操作(例:输入框的 “清空” 按钮)。

5-2 Button的使用

1.Button的创建语法格式

(1)使用tkinter创建Button控件的语法格式

注:master是父窗口, options是其他参数

btn = tkinter.Button(master, options, ...)

(2)使用tkinter.ttk创建Button控件的语法格式

注:master是父窗口, options是其他参数

btn = tkinter.ttk.Button(master, options, ...)

2.Button构造方法内的参数说明

(1)tkinter.Button的参数详解

参数名称参数作用数据类型传参示例
master指定按钮的父容器(如窗口、Frame 等),决定按钮的归属层级。MiscNoneMisc 是 Tkinter 控件的基类,包括 TkFrame 等)master=rootmaster=frame1
cnf以字典形式批量设置其他参数(较少直接使用,通常直接传关键字参数)。dict[str, Any]Nonecnf={"text": "按钮", "command": func}
activebackground按钮处于 active 状态(鼠标按下时)的背景色。字符串(颜色名或十六进制值)activebackground="lightblue"activebackground="#EEEEEE"
activeforeground按钮处于 active 状态鼠标按下时的文本颜色。字符串(颜色名或十六进制值)activeforeground="red"activeforeground="#FF0000"
anchor按钮内文本 / 图像的对齐方式(相对于按钮左上角)。字面量:"nw"(左上)、"n"(上)、"ne"(右上)、"w"(左)、"center"(居中)、"e"(右)、"sw"(左下)、"s"(下)、"se"(右下)anchor="w"(左对齐)、anchor="ne"(右上对齐)
background按钮默认状态的背景色(与 bg 作用相同)。字符串(颜色名或十六进制值)background="white"background="#FFFFFF"
bd按钮边框宽度(与 borderwidth 作用相同)。字符串或浮点数(像素值)bd=2bd="3"
bg按钮默认状态的背景色(background 的简写)。字符串(颜色名或十六进制值)bg="gray"bg="#888888"
bitmap按钮上显示的内置位图(如 errorinfo 等,与 image 互斥)。字符串(位图名称)bitmap="error"bitmap="hourglass"
border按钮边框宽度(与 borderwidth 作用相同,较少使用)。字符串或浮点数(像素值)border=1border="4"
borderwidth按钮边框宽度(像素值,决定边框粗细)。字符串或浮点数(像素值)borderwidth=2borderwidth="5"
command按钮被点击时触发的回调函数(无参数函数或 lambda 表达式)。字符串(Tcl 命令)或无参函数command=submit_funccommand=lambda: print("点击")
compound文本与图像的混合显示模式(当同时设置 textimage 时生效)。字面量:"top"(图上文本下)、"left"(图左文本右)、"center"(图文重叠)、"right"(图右文本左)、"bottom"(图下文本上)、"none"(仅显示图像)compound="left"compound="top"
cursor鼠标悬停在按钮上时的光标样式(如箭头、手型等)。字符串(光标名称)或多元素元组(系统相关光标定义)cursor="hand2"(手型)、cursor="arrow"(箭头)
default按钮的默认状态(仅用于对话框中的按钮,如 OK 按钮设为默认)。字面量:"normal"(无默认)、"active"(默认激活)、"disabled"(禁用)default="active"
disabledforeground按钮处于 disabled 状态(禁用)时的文本颜色。字符串(颜色名或十六进制值)disabledforeground="gray"disabledforeground="#AAAAAA"
fg按钮默认状态的文本颜色(foreground 的简写)。字符串(颜色名或十六进制值)fg="black"fg="#000000"
font按钮文本的字体设置(字体名、大小、样式)。字体元组、字符串或 Font 对象font=("SimHei", 12, "bold")font="Arial 10 italic"
foreground按钮默认状态的文本颜色(与 fg 作用相同)。字符串(颜色名或十六进制值)foreground="blue"foreground="#0000FF"
height按钮高度(单位:文本行数,图像按钮则为像素)。字符串或浮点数height=2(2 行高)、height="3"
highlightbackground按钮未获得焦点时,焦点高亮边框的颜色。字符串(颜色名或十六进制值)highlightbackground="white"
highlightcolor按钮获得焦点时,焦点高亮边框的颜色字符串(颜色名或十六进制值)highlightcolor="blue"
highlightthickness焦点高亮边框的宽度(0 表示隐藏焦点边框)。字符串或浮点数(像素值)highlightthickness=1highlightthickness="0"
image按钮上显示的图像(PhotoImage 对象或图像路径,与 bitmap 互斥)。_Image(如 PhotoImage)或字符串(图像路径)image=img_objimg_obj = PhotoImage(file="btn.png")
justify多行文本的对齐方式(仅当文本换行时生效)。字面量:"left"(左对齐)、"center"(居中)、"right"(右对齐)justify="left"justify="center"
name按钮的内部名称(用于 Tcl 命令引用,通常无需手动设置)。字符串name="submit_btn"
overrelief鼠标悬停时按钮的边框样式(覆盖 relief 设置)。字面量:"raised"(凸起)、"sunken"(凹陷)、"flat"(扁平)、"ridge"(脊状)、"solid"(实线)、"groove"(凹槽)overrelief="sunken"overrelief="ridge"
padx按钮文本 / 图像与左右边框的水平间距(像素)。字符串或浮点数padx=5padx="10"
pady按钮文本 / 图像与上下边框的垂直间距(像素)。字符串或浮点数pady=3pady="8"
relief按钮的边框样式(默认 raised)。字面量:"raised"(凸起)、"sunken"(凹陷)、"flat"(扁平)、"ridge"(脊状)、"solid"(实线)、"groove"(凹槽)relief="solid"relief="flat"
repeatdelay按住按钮时,首次触发 command 的延迟时间(毫秒,需配合 repeatinterval)。整数repeatdelay=500(按住 500ms 后首次触发)
repeatinterval按住按钮时,触发 command 的间隔时间(毫秒)。整数repeatinterval=100(每隔 100ms 触发一次)
state按钮的启用状态(默认 normal)。字面量:"normal"(正常可点击)、"active"(激活态)、"disabled"(禁用)state="disabled"state="normal"
takefocus按钮是否接受键盘焦点(按 Tab 键可聚焦,聚焦后按 Enter 触发点击)。整数、空字符串 ""、返回布尔值的函数或 Nonetakefocus=Truetakefocus=1(接受焦点);takefocus=False(不接受)
text按钮上显示的文本内容(支持 \n 换行)。字符串或浮点数text="点击提交"text="确定\n(Enter)"
textvariable绑定动态文本变量(变量值变化时,按钮文本同步更新)。Variable 子类(如 StringVarIntVartextvariable=btn_varbtn_var = StringVar(value="初始文本")
underline文本中下划线的位置(从 0 开始索引,-1 表示无下划线)。整数underline=0(第 1 个字符下划线)、underline=2
width按钮宽度(单位:字符数,图像按钮则为像素)。字符串或浮点数width=10(10 字符宽)、width="15"
wraplength文本自动换行的宽度阈值(超过该宽度则换行,单位:像素)。字符串或浮点数wraplength=100(超过 100 像素换行)、wraplength="150"

说明:

  • 功能相同的参数(如 bgbackgroundbdborderwidth)通常选一种即可,推荐使用完整名称(如 background)提高可读性。
  • 颜色参数支持多种格式:颜色名(如 red)、十六进制值(如 #FF0000)、RGB 元组(如 (255,0,0),部分版本支持)。
  • 光标样式依赖系统支持,常用值包括 arrow(箭头)、hand2(手型)、xterm(文本光标)等。

(2)ttk.Button的参数详解

参数名称参数作用数据类型传参示例
master指定按钮的父容器(如窗口、Frame 等),决定按钮的归属层级。MiscNoneMisc 是 Tkinter 控件的基类,包括 TkFrame 等)master=rootmaster=frame1
class_按钮的样式类名称(用于样式继承,与 style 配合使用,较少手动设置)。字符串class_="TButton"(继承默认按钮样式类)
command按钮被点击时触发的回调函数(无参数函数或 lambda 表达式)。任意可调用对象(函数、方法等)command=submit_funccommand=lambda: print("点击")
compound文本与图像的混合显示模式(当同时设置 textimage 时生效)。字面量或对应整数:"top"(图上文本下)、"left"(图左文本右)、"center"(图文重叠)、"right"(图右文本左)、"bottom"(图下文本上)、"none"(仅显示图像)compound="left"compound="top"
cursor鼠标悬停在按钮上时的光标样式(如箭头、手型等)。字符串(光标名称)或系统支持的光标定义cursor="hand2"(手型)、cursor="arrow"(箭头)
default按钮的默认状态(仅用于对话框中的按钮,如 OK 按钮设为默认)。字面量:"normal"(无默认)、"active"(默认激活)、"disabled"(禁用)default="active"
image按钮上显示的图像(PhotoImage 对象或图像路径,与文本可通过 compound 混合)。图像对象(如 PhotoImage)或字符串(图像路径)image=img_objimg_obj = PhotoImage(file="btn.png")
name按钮的内部名称(用于 Tcl 命令引用,通常无需手动设置)。字符串name="submit_btn"
padding按钮内部的内边距(文本 / 图像与边框的间距),支持统一或单独设置上下左右间距。整数(统一间距)、二元组((x, y) 分别表示水平和垂直间距)、四元组((left, top, right, bottom)padding=5(四边均 5 像素)、padding=(10, 5)(水平 10,垂直 5)、padding=(2, 3, 2, 3)
state按钮的启用状态(默认 normal)。字符串:"normal"(正常可点击)、"disabled"(禁用)、"active"(激活态)state="disabled"state="normal"
style按钮绑定的样式名称(通过 ttk.Style() 自定义的样式,用于统一外观)。字符串style="Primary.TButton"(应用名为 Primary.TButton 的自定义样式)
takefocus按钮是否接受键盘焦点(按 Tab 键可聚焦,聚焦后按 Enter 触发点击)。布尔值、空字符串 ""None(自动判断)takefocus=True(接受焦点)、takefocus=False(不接受)
text按钮上显示的文本内容(支持 \n 换行)。字符串或浮点数text="点击提交"text="确定\n(Enter)"
textvariable绑定动态文本变量(变量值变化时,按钮文本同步更新)。Variable 子类(如 StringVarIntVartextvariable=btn_varbtn_var = StringVar(value="初始文本")
underline文本中下划线的位置(从 0 开始索引,-1 表示无下划线)。整数underline=0(第 1 个字符下划线)、underline=2
width按钮的宽度(单位:字符数,0 表示自适应文本长度,空字符串 "" 表示默认宽度)。整数或空字符串 ""width=10(10 字符宽)、width=0(自适应)、width=""(默认宽度)

关键特性说明:

  • 样式管理ttk.Button 不支持 bgfg 等直接样式参数,外观完全由 style 参数绑定的 ttk.Style 控制,便于批量统一界面风格。
  • 简化参数:相比 tkinter.Button,减少了大量样式相关参数(如 reliefborderwidth),专注于功能逻辑。
  • 兼容性:样式会自动适配操作系统主题(如 Windows 的圆角按钮、macOS 的原生按钮样式),视觉一致性更好。
  • padding 灵活性:支持更精细的内边距设置,比 tkinter.Buttonpadx/pady 更强大。

3.Button控件类的方法

tkinter.Buttonttk.Button 均继承自 Tkinter 的基础控件类,因此它们的方法大部分相同(核心功能一致),仅在少数样式相关方法上有细微差异。以下是 Button 控件类的所有常用方法,按功能分类整理:

(1)核心交互方法

方法名作用说明适用控件
invoke()模拟按钮被点击,触发 command 绑定的回调函数(返回函数的返回值;若按钮禁用,返回 None)。两者均适用
flash()按钮闪烁效果:快速切换 activenormal 状态(各切换几次),用于提示用户注意。两者均适用

(2)属性配置方法

方法名作用说明适用控件
configure(**options)动态修改按钮的参数(如文本、状态、样式等),参数与构造函数一致。例如 btn.configure(text="新文本", state="disabled")两者均适用
cget(option)获取指定参数的当前值(返回参数值)。例如 btn.cget("text") 返回按钮当前文本。两者均适用
keys()返回按钮所有可配置的参数名称列表(字符串列表)。例如 print(btn.keys()) 可查看所有参数。两者均适用

(3)焦点管理方法

方法名作用说明适用控件
focus_set()使按钮获得键盘焦点(聚焦后,按 Enter 键可触发点击)。两者均适用
focus_get()返回当前拥有键盘焦点的控件(注意:这是顶层窗口方法,按钮调用时等价于 root.focus_get())。两者均适用
focus()按钮获取焦点两者均适用

(4)布局与尺寸方法

方法名作用说明适用控件
winfo_width()返回按钮当前宽度(单位:像素)。两者均适用
winfo_height()返回按钮当前高度(单位:像素)。两者均适用
winfo_x()返回按钮左上角相对于父容器的 x 坐标(单位:像素)。两者均适用
winfo_y()返回按钮左上角相对于父容器的 y 坐标(单位:像素)。两者均适用
update_idletasks()强制刷新按钮的外观(立即更新未完成的绘制任务,解决重影、延迟显示等问题)。两者均适用

(5)生命周期方法

方法名作用说明适用控件
destroy()销毁按钮(从父容器中移除,释放占用的资源,之后无法再使用)。两者均适用
pack_forget()隐藏按钮(不销毁,仅从布局中移除,可通过 pack() 重新显示)。两者均适用(仅用于 pack 布局)
grid_forget()隐藏按钮(不销毁,仅从布局中移除,可通过 grid() 重新显示)。两者均适用(仅用于 grid 布局)
place_forget()隐藏按钮(不销毁,仅从布局中移除,可通过 place() 重新显示)。两者均适用(仅用于 place 布局)
forget()隐藏按钮(作用于与pack_forget\grid_forget\place_forget一样)两者均适用

(6)事件绑定方法

方法名作用说明适用控件
bind(sequence, func, add=None)为按钮绑定事件(如点击、鼠标悬停等),sequence 为事件类型(如 <Button-1>),func 为回调函数。两者均适用
unbind(sequence, funcid=None)解除按钮绑定的事件(sequence 为事件类型,funcid 为绑定标识,可选)。两者均适用
bind_all(sequence, func, add=None)为所有控件绑定全局事件(按钮调用时,等价于 root.bind_all())。两者均适用

(7)样式相关方法(仅 ttk.Button 特有)

方法名作用说明适用控件
configure_style()配合 ttk.Style 动态修改按钮绑定的样式(需通过 style 参数关联样式类)。例如 style.configure("My.TButton", font=("Arial", 10))ttk.Button
state([stateSpec])查看或修改按钮的状态(如 state("disabled") 禁用按钮,state("!disabled") 启用按钮,无参数时返回当前状态)。ttk.Button

5-3 案例

1.tkinter.Button的参数使用

(1)master和cnf参数:master为控件的父窗口,cnf以字典形式批量设置其他参数(较少直接使用,通常直接传关键字参数)。

import tkinter as tk

if __name__ == '__main__':
    root = tk.Tk()
    
    # btn的父窗口说root
    # 使用cnf参数设置按钮的文本内容为button
    btn = tk.Button(master=root,
                    cnf={"text": "button"})
    btn.pack(pady=20, padx=10)
    
    root.mainloop()

在这里插入图片描述

(2)text参数:设置按钮的文本内容

import tkinter as tk

if __name__ == '__main__':
    root = tk.Tk()
    
    # 通过text参数设置按钮文本内容
    btn = tk.Button(master=root,
                    text="button")
    btn.pack(pady=20, padx=10)
    
    root.mainloop()

在这里插入图片描述

(3)activebackground: 按钮处于 active 状态(鼠标按下时)的背景色。

import tkinter as tk

if __name__ == '__main__':
    root = tk.Tk()

    btn1 = tk.Button(master=root,
                     text="button1")
    btn1.pack()
	
    # 通过activebackground参数设置鼠标按下按钮时的背景色
    btn2 = tk.Button(master=root,
                     text="button2",
                     activebackground="lightblue")
    btn2.pack(pady=20, padx=10)

    root.mainloop()

在这里插入图片描述

(4)activeforeground: 按钮处于 active 状态(鼠标按下时)的文字颜色

import tkinter as tk

if __name__ == '__main__':
    root = tk.Tk()

    btn1 = tk.Button(master=root,
                     text="button1")
    btn1.pack()
	
	# 通过activeforeground参数设置鼠标按下按钮时的背景色
    btn2 = tk.Button(master=root,
                     text="button2",
                     activeforeground="lightblue")
    btn2.pack(pady=20, padx=10)

    root.mainloop()

在这里插入图片描述

(5)width和height参数:设置按钮的宽和高

import tkinter as tk

if __name__ == '__main__':
    root = tk.Tk()

    btn1 = tk.Button(master=root,
                     text="button1")
    btn1.pack()

    # 通过width和height参数设置按钮的宽和高
    btn2 = tk.Button(master=root,
                     text="button2",
                     width=10,
                     height=5)
    btn2.pack(pady=20, padx=10)

    root.mainloop()

在这里插入图片描述

(6)anchor:按钮内文本 / 图像的对齐方式(相对于按钮左上角)。

import tkinter as tk

if __name__ == '__main__':
    root = tk.Tk()

    btn1 = tk.Button(master=root,
                     text="button1",
                     width=10,
                     height=5)
    btn1.pack()

    # 通过anchor参数设置按钮内文本的对齐方式
    btn2 = tk.Button(master=root,
                     text="button2",
                     width=10,
                     height=5,
                     anchor=tk.W)
    btn2.pack(pady=20, padx=10)

    root.mainloop()

在这里插入图片描述

(7)bg或background:设置按钮背景颜色

import tkinter as tk

if __name__ == '__main__':
    root = tk.Tk()

    btn1 = tk.Button(master=root,
                     text="button1",
                     width=10,
                     height=5)
    btn1.pack()

    # 通过bg或background参数设置按钮背景颜色
    btn2 = tk.Button(master=root,
                     text="button2",
                     width=10,
                     height=5,
                     anchor=tk.W,
                     bg="yellow")
    btn2.pack(pady=20, padx=10)

在这里插入图片描述

(8)bitmap: 按钮上显示的内置位图(如 errorinfo 等,与 image 互斥)。

位图参数的取值有:‘error’,‘gray75’,‘gray50’,‘gray25’,‘gray12’,‘hourglass’,‘info’,‘questhead’, ‘question’, ‘warning’

import tkinter as tk

if __name__ == '__main__':
    root = tk.Tk()
	
    # 位图参数的取值列表
    bitmaps = ['error', 'gray75', 'gray50', 'gray25', 'gray12',
               'hourglass', 'info', 'questhead', 'question', 'warning']

    # 使用bitmap参数设置按钮上显示的内置位图
    for bitmap_string in bitmaps:
        tk.Button(master=root,
                  bitmap=bitmap_string).pack(side=tk.LEFT,
                                             padx=5,
                                             fill=tk.X,
                                             expand=True)

    root.mainloop()

在这里插入图片描述

(9)bd、borderwidth、border: 按钮边框宽度(像素值,决定边框粗细)。

import tkinter as tk

if __name__ == '__main__':
    root = tk.Tk()

    btn1 = tk.Button(root,
                     text="按钮控件1")
    btn1.pack(pady=10)
	
    # 设置bd参数,让按钮边框变得更粗一些
    btn2 = tk.Button(root,
                     text="按钮控件2",
                     bd=10)
    btn2.pack(pady=10)

    root.mainloop()

在这里插入图片描述

(10)command:按钮被点击时触发的回调函数。

import tkinter as tk
from tkinter import messagebox


def show_btn_info():
    messagebox.showinfo(title="tk",
                        message="这是一消息框")


if __name__ == '__main__':
    root = tk.Tk()
	
    # 设置按钮command参数,当按下按钮时,使其执行show_btn_info函数,打开一个消息框
    btn1 = tk.Button(root,
                     text="按钮控件1",
                     command=show_btn_info)
    btn1.pack(pady=10)

    root.mainloop()

在这里插入图片描述

(11)compound:文本与图像的混合显示模式

import tkinter as tk

if __name__ == '__main__':
    root = tk.Tk()
	
    # 在按钮控件上添加位图图片,并设置compoud="left",文本与图像共存,图左文字居右
    btn1 = tk.Button(root,
                     text="按钮控件1",
                     bitmap="info",
                     compound="left")
    btn1.pack(pady=10)

    root.mainloop()

在这里插入图片描述

(12)cursor:鼠标悬停在按钮上时的光标样式(如箭头、手型等)

注:光标形状及其值于Label控件的一样

import tkinter as tk

if __name__ == '__main__':
    root = tk.Tk()
	
	# 设置按钮控件的cursor参数,当鼠标悬停在按钮上面时,鼠标变成手型
    btn1 = tk.Button(root,
                     text="按钮控件1",
                     cursor="hand2")
    btn1.pack(pady=20, anchor=tk.CENTER)
    root.mainloop()

(13)default :按钮的默认状态(仅用于对话框中的按钮,如 OK 按钮设为默认)。

import tkinter as tk

if __name__ == '__main__':
    root = tk.Tk()

    btn1 = tk.Button(root,
                     text="按钮控件1")
    btn1.pack(pady=20, anchor=tk.CENTER)
	
    # 设置按钮的default参数
    btn2 = tk.Button(root,
                     text="按钮控件2",
                     default=tk.ACTIVE)
    btn2.pack(pady=20, anchor=tk.CENTER)

    root.mainloop()

在这里插入图片描述

# 使用Button的default参数来模拟当第一次按下按钮后,按钮被选中,当再次按下按钮后按钮不被选中
import tkinter as tk


def set_active(event: tk.Event):
    widget: tk.Button = event.widget

    if widget.cget("default") != tk.ACTIVE:
        widget.configure(default=tk.ACTIVE)
    else:
        widget.configure(default=tk.DISABLED)


if __name__ == '__main__':
    root = tk.Tk()

    btn1 = tk.Button(root,
                     text="按钮控件1")
    btn1.pack(pady=20, anchor=tk.CENTER)

    btn2 = tk.Button(root,
                     text="按钮控件2")
    btn2.pack(pady=20, anchor=tk.CENTER)
	
    # 绑定鼠标左键按钮事件
    btn1.bind("<Button-1>", set_active)
    btn2.bind("<Button-1>", set_active)
    root.mainloop()

第一次按下按钮,按钮选中:

在这里插入图片描述

第二次按下按钮,不选中按钮2:

在这里插入图片描述

(14)fg/foreground:按钮文本颜色

import tkinter as tk

if __name__ == '__main__':
    root = tk.Tk()
    
    # 通过fg/foreground参数设置按钮文本内容颜色
    btn = tk.Button(root, text="button",
                    fg="purple")
    btn.pack()

    btn2 = tk.Button(root, text="button",
                     foreground="purple")
    btn2.pack()
    root.mainloop()

在这里插入图片描述

(15)font:按钮文本内的字体和大小

font: 设置文字字形,参数内容如下
family: 字形,如Times
size: 字体大小,单位像素
weight: 字体的粗细,如bold、normal
slat: 字体倾斜,如italic、roman
underline: 字体是否要有下划线
overstrike: 字体是否要有删除线

**注:**元组内第一个值和第二个值必须要按参数的顺序传参,不能颠倒顺序,其他的在传参时不受顺序影响,而且参数可以搭配使用

比如:只设置字体和字体大小,font=(“Times”, 20)

import tkinter as tk

if __name__ == '__main__':
    root = tk.Tk()
    btn = tk.Button(root, text="button",
                    fg="purple",
                    font=("Times", 
                          20, 
                          "bold", 
                          "italic", 
                          "underline", 
                          "overstrike"))
    btn.pack()

    btn2 = tk.Button(root, text="button",
                     fg="purple",
                     font=("Times", 20, "overstrike", "bold", "underline",))
    btn2.pack()
    root.mainloop()

在这里插入图片描述

(16)highlightcolor/highlightthickness:按钮获得焦点时焦点边框的的宽度和边框颜色

highlightbackground/highlightthickness:按钮未获得焦点时焦点边框的的宽度和边框颜色

:这三个参数会受操作系统和主题外观影响的影响,可能不会完全遵循你设置。 有时,焦点指示器就是一个很薄的虚线框,或者只是按钮上的微妙变化(例如稍微加粗的边框)。除此,在Python3.13中highlightcolor的颜色设定会受fg参数的影响

import tkinter as tk
# 导入tkinter中的常量
from tkinter.constants import *

if __name__ == '__main__':
    root = tk.Tk()
    # 设置参数highlightcolor/highlightthickness/highlightbackground
    btn = tk.Button(root, text="button",
                    highlightcolor="blue",
                    highlightthickness=2,
                    highlightbackground="gray")
    # 在设置fill参数值,使用的是常量BOTH来代替字符串“both”
    btn.pack(fill=BOTH, expand=True)
	
    # 初始获得焦点
    btn.focus_set()  

    root.mainloop()

在这里插入图片描述

(17)image:设置图像,需要借助PhotoImage显示PGM, PPM, GIF, PNG格式图像,显示jpg格式图像需要借助PIL的Image和ImageTK

注:tkinter.PhotoImage() 适合处理简单的 PGM, PPM, GIF, PNG,GIF 图像,支持基本的缩放和像素操作。对于复杂场景(如多格式支持、高质量缩放),建议结合 Pillow 库使用。注意保持对象引用和内存管理,避免图像显示异常。

通过PIL.Image和PIL.ImageTk在按钮上显示图片

import tkinter as tk
# 从PIL中导入Image、ImageTk
from PIL import Image, ImageTk

if __name__ == '__main__':
    root = tk.Tk()
	
    # 使用Image.open("图片片路径")打开图片
    photo = Image.open("pycharm.png")
    
    # 调整图片大小
    photo = photo.resize(size=(100, 100))
    # 将photo转成PhotoImage
    image = ImageTk.PhotoImage(image=photo)
	
    #通过image参数设置按钮图片
    btn = tk.Button(root,
                    image=image)
    
    # 保持引用,防止被垃圾回收
    btn.image = image
    btn.pack()

    root.mainloop()

在这里插入图片描述

通过tkinter.PhotoImage设置图片

import tkinter as tk

if __name__ == '__main__':
    root = tk.Tk()
	
    # 使用tk.PhotoImage加载图片
    image = tk.PhotoImage(file="pycharm.png")
    # 将图缩小为原图的1/2*2,即1/4
    image = image.subsample(2, 2)
	
	# 通过image参数设置按钮图片
    btn = tk.Button(root,
                    image=image)
    
    # 保持引用,防止被垃圾回收
    btn.image = image

    btn.pack()

    root.mainloop()

在这里插入图片描述

图文混排:需要用到compound参数

import tkinter as tk

if __name__ == '__main__':
    root = tk.Tk()
	
    # 使用tk.PhotoImage加载图片
    image = tk.PhotoImage(file="pycharm.png")
    # 将图缩小为原图的1/2*2,即1/4
    # image = image.subsample(2, 2)

    # 通过image参数设置按钮图片
    btn = tk.Button(root,
                    text="button"
                    image=image,
                    compound="left",  # 图左文字居右
                   )

    # 保持引用,防止被垃圾回收
    btn.image = image

    btn.pack()

    root.mainloop()

在这里插入图片描述

(18)relief:按钮的边框样式(默认 raised

import tkinter as tk

if __name__ == '__main__':
    root = tk.Tk()
	
    # relief参数取值列表
    reliefs: list = ["raised", "sunken", "flat", "ridge", "solid", "groove"]
	
    # 使用循环创建并布局控件
    for relief in reliefs:
        btn = tk.Button(root,
                        text=relief,  # 按钮上的文本内容
                        relief=relief,  # 通过relief参数值设置按钮边框样式
                        bg="#4582ec")  # 设置背景颜色
		
        # 布局按钮
        btn.pack(side=tk.LEFT, padx=3)

    root.mainloop()

在这里插入图片描述

(19)overrelief:鼠标悬停时按钮的边框样式(覆盖 relief 设置)。

字面量:"raised"(凸起)、"sunken"(凹陷)、"flat"(扁平)、"ridge"(脊状)、"solid"(实线)、"groove"(凹槽)

import tkinter as tk

if __name__ == '__main__':
    root = tk.Tk()
	
    # relief参数取值列表
    reliefs: list = ["raised", "sunken", "flat", "ridge", "solid", "solid", "groove"]
	
    # 使用循环创建并布局控件
    for relief in reliefs:
        btn = tk.Button(root,
                        text=relief,  # 按钮上的文本内容
                        relief=relief,  # 按钮边框样式
                        bg="#4582ec", # 按钮背景颜色
                        overrelief="groove") # 鼠标悬停在按钮上时的按钮边框样式

        btn.pack(side=tk.LEFT, padx=3)

    root.mainloop()

在这里插入图片描述

(20)state:按钮的启用状态(默认 normal)。 字面量:"normal"(正常可点击)、"active"(激活态)、"disabled"(禁用)

import tkinter as tk

if __name__ == '__main__':
    root = tk.Tk()
	
    # 按钮状态值列表
    state_list: list = ["normal", "active", "disabled"]
	
    # 使用循环创建并布局控件 
    for state in state_list:
        button = tk.Button(root,
                           text=state,  # 按钮上的文本内容
                           state=state, # 设置按钮的state参数
                           activebackground="yellow" # 设置当按钮被激活时的背景颜色
                          )
        button.pack()

    root.mainloop()

在这里插入图片描述

(21)disabledforeground:按钮处于 disabled 状态(禁用)时的文本颜色。

import tkinter as tk

if __name__ == '__main__':
    root = tk.Tk()
	
    # 按钮状态值列表
    state_list: list = ["normal", "active", "disabled"]
	
    # 使用循环创建并布局控件 
    for state in state_list:
        button = tk.Button(root,
                           text=state,  # 按钮上的文本内容
                           state=state, # 设置按钮的state参数
                           activebackground="yellow", # 设置当按钮被激活时的背景颜色
                           disabledforeground="purple" # 按钮处于禁用状态时的文本颜色
                          )
        button.pack()

    root.mainloop()

在这里插入图片描述

(22)underline:文本中下划线的位置(从 0 开始索引,-1 表示无下划线)。

import tkinter as tk

if __name__ == '__main__':
    root = tk.Tk()
	
    # 通过设置underline=0,使按钮文本的第一个字有下划线
    button = tk.Button(root, text="button",
                       underline=0)
    button.pack()

    root.mainloop()

在这里插入图片描述

(23)justify:设置按钮的文本对齐方式,值有:“left”, “center”, “right”

import tkinter as tk

if __name__ == '__main__':
    root = tk.Tk()
	
    button = tk.Button(root, text="button\n这是一个tkinter的按钮控件")
    button.pack()
	
    # 通过justify设置按钮的文本对齐方式为左对齐
    button2 = tk.Button(root, text="button\n这是一个tkinter的按钮控件",
                        justify="left")
    button2.pack()
    root.mainloop()

在这里插入图片描述

(24)padx/pady:按钮文本 / 图像与左右/上下边框的水平/垂直间距(像素)。

import tkinter as tk

if __name__ == '__main__':
    root = tk.Tk()

    button = tk.Button(root, text="button")
    button.pack()
	
    # 设置按钮文本与左右和上下边框的水平和垂直间距
    button2 = tk.Button(root, text="button2",
                        padx=5,
                        pady=5)
    button2.pack()

    root.mainloop()

在这里插入图片描述

(25)wraplength: 文本自动换行的宽度阈值(超过该宽度则换行,单位:像素)。

import tkinter as tk

if __name__ == '__main__':
    root = tk.Tk()

    button = tk.Button(root, text="button,这是一个tkinter的按钮控件")
    button.pack()
	
    # 设置warplenth,当文本宽度超过100像素时,文本自动换行
    button2 = tk.Button(root, text="button2,这是一个tkinter的按钮控件",
                        wraplength=100)
    button2.pack()

    root.mainloop()

在这里插入图片描述

2.ttk.Button的参数使用

(1)master: 按钮的父容器,text: 按钮的文本内容

import tkinter as tk
from tkinter import ttk

if __name__ == '__main__':
    root = tk.Tk()
	
    # 设置master和text参数
    button = ttk.Button(master=root, text="button")
    button.pack()

    root.mainloop()

在这里插入图片描述

(2)command:按钮被点击时触发的回调函数(无参数函数或 lambda 表达式)。

import tkinter as tk
from tkinter import ttk
from tkinter.messagebox import showinfo

if __name__ == '__main__':
    root = tk.Tk()
	
    # 设置command参数,执行回调函数
    button = ttk.Button(master=root, text="button",
                        command=lambda: showinfo(title="showinfo",
                                                 message="按钮执行了command"))
    button.pack()

    root.mainloop()

在这里插入图片描述

(3)image: 设置按钮上的图片,设置方法和tkinter.Button的image参数一样

import tkinter as tk
from tkinter import ttk
from tkinter.messagebox import showinfo

if __name__ == '__main__':
    root = tk.Tk()
	
    # 加载图片
    image = tk.PhotoImage(file="pycharm.png")
    # 将图缩小成原图的1/4大小
    image = image.subsample(x=2, y=2)
    # 设置按钮上的图片
    button = ttk.Button(master=root, image=image)
    button.pack()
    # 保持图片引用, 防止被垃圾回收
    button.image = image

    root.mainloop()

在这里插入图片描述

(4)compound: 按钮的文本和图片混排

字面量:"top"(图上文本下)、"left"(图左文本右)、"center"(图文重叠)、"right"(图右文本左)、"bottom"(图下文本上)、"none"(仅显示图像)

import tkinter as tk
from tkinter import ttk

if __name__ == '__main__':
    root = tk.Tk()
	
    # 加载图片
    image = tk.PhotoImage(file="pycharm.png")
    # 将图缩小成原图的1/4大小
    image = image.subsample(x=2, y=2)
	# 设置按钮上的图片和文字,通过compound设置图左文本右
    button = ttk.Button(master=root,
                        text="button",
                        image=image,
                        compound="right")
    button.pack()
    # 保持图片引用, 防止被垃圾回收
    button.image = image

    root.mainloop()

在这里插入图片描述

(5)cursor:鼠标悬停在按钮上时的光标样式(如箭头、手型等)

import tkinter as tk
from tkinter import ttk

if __name__ == '__main__':
    root = tk.Tk()

    button = ttk.Button(master=root,
                        text="button",
                        cursor="hand2"
                        )
    button.pack()

    root.mainloop()

(6)default:按钮的默认状态(仅用于对话框中的按钮,如 OK 按钮设为默认)。 字面量:"normal"(无默认)、"active"(默认激活)、"disabled"(禁用)

import tkinter as tk
from tkinter import ttk

if __name__ == '__main__':
    root = tk.Tk()
	
    button = ttk.Button(master=root,
                        text="button",
                        cursor="hand2",
                        default="active")
    button.pack()

    root.mainloop()

在这里插入图片描述

**(7)padding: 按钮内部的内边距(文本 / 图像与边框的间距),支持统一或单独设置上下左右间距。 整数(统一间距)、二元组((x, y) 分别表示水平和垂直间距)、四元组((left, top, right, bottom)) **

import tkinter as tk
from tkinter import ttk

if __name__ == '__main__':
    root = tk.Tk()
	
    # 设置padding,使得按钮内部的水平和垂直内边距为5
    button = ttk.Button(master=root,
                        text="button",
                        padding=(5, 5)
                       )
    button.pack()

    root.mainloop()

在这里插入图片描述

(8)state: 钮的启用状态(默认 normal)。 字面量:"normal"(正常可点击)、"active"(激活态)、"disabled"(禁用)

import tkinter as tk
from tkinter import ttk

if __name__ == '__main__':
    root = tk.Tk()

    state_list: list = ["normal", "active", "disabled"]

    for state in state_list:
        button = ttk.Button(root,
                            text=state,
                            state=state)
        button.pack()

    root.mainloop()

在这里插入图片描述

(9)style: 设置按钮样式

import tkinter as tk
from tkinter import ttk

if __name__ == '__main__':
    root = tk.Tk()
    root.title("模仿ttkbootstrap风格")
    style = ttk.Style()
    style.theme_use('clam')  # 选择兼容性较好的主题

    # 成功按钮样式(绿色)
    style.configure('Success.TButton',
                    font=('Segoe UI', 9),
                    background='#28a745',
                    foreground='white',
                    padding=(8, 4),
                    relief='flat')  # 扁平风格
    # 设置style的指定属性的动态值。
    style.map('Success.TButton',
              background=[('active', '#218838'), 
                          ('pressed', '#1e7e34')])
	
    button = ttk.Button(root, text="success",
                        style="Success.TButton")
    button.pack()
    root.mainloop()

在这里插入图片描述

(11)textvariable: 绑定动态文本变量(变量值变化时,按钮文本同步更新)。

与组件相关的4个子类别的数据类型:
    x = IntVar(): 整数变量, 默认是0
    x = DoubleVar(): 浮点型变量, 默认是0.0
    x = StringVar(): 字符串变量, 默认是""
    x = BooleanVar(): 布尔型变量, True是1, False是0,默认为False
import tkinter as tk
from tkinter import ttk
from tkinter.messagebox import *


def get_var():
    showinfo(title="textvariable",
             message=f"textvariable:{var.get()}")


if __name__ == '__main__':
    root = tk.Tk()
	
    # 创建字符串变量
    var = tk.StringVar()
    # 设置变量的值
    var.set("get_var")
    # 通过按钮的textvariableb绑定变量
    button = ttk.Button(root, textvariable=var,
                        command=get_var)
    button.pack()

    root.mainloop()

在这里插入图片描述
(12)underline:和tkinter.Button的underline用法一样
(13)width:和tkinter.Button的width用法一样

Abstract Describes the Tkinter widget set for constructing graphical user interfaces (GUIs) in the Python programming language. This publication is available in Web form1 and also as a PDF document2. Please forward any comments to tcc-doc@nmt.edu. Table of Contents 1. What is Tkinter?.......................................................................................................................3 2. A minimal application..............................................................................................................3 3. Definitions..............................................................................................................................4 4. Layout management.................................................................................................................5 4.1. The .grid() method....................................................................................................5 4.2. Other grid management methods...................................................................................6 4.3. Configuring column and row sizes.................................................................................7 4.4. Making the root window resizeable................................................................................8 5. Standard attributes...................................................................................................................8 5.1. Dimensions...................................................................................................................9 5.2. The coordinate system...................................................................................................9 5.3. Colors...........................................................................................................................9 5.4. Type fonts...................................................................................................................10 5.5. Anchors......................................................................................................................11 5.6. Relief styles.................................................................................................................12 5.7. Bitmaps.......................................................................................................................12 5.8. Cursors.......................................................................................................................12 5.9. Images........................................................................................................................14 5.10. Geometry strings........................................................................................................14 5.11. Window names...........................................................................................................15 5.12. Cap and join styles.....................................................................................................15 5.13. Dash patterns.............................................................................................................16 5.14. Matching stipple patterns............................................................................................16 6. The Button widget................................................................................................................17 7. The Canvas widget................................................................................................................19 7.1. Canvas coordinates......................................................................................................20 7.2. The Canvas display list................................................................................................20 7.3. Canvas object IDs........................................................................................................21 7.4. Canvas tags................................................................................................................21 1http://www.nmt.edu/tcc/help/pubs/tkinter/ 2http://www.nmt.edu/tcc/help/pubs/tkinter/tkinter.pdf 1 Tkinter reference New Mexico Tech Computer Center 7.5. CanvastagOrId arguments......................................................................................21 7.6. Methods on Canvas widgets........................................................................................21 7.7. Canvas arc objects.......................................................................................................26 7.8. Canvas bitmap objects.................................................................................................28 7.9. Canvas image objects..................................................................................................29 7.10. Canvas line objects.....................................................................................................29 7.11. Canvas oval objects....................................................................................................31 7.12. Canvas polygon objects..............................................................................................32 7.13. Canvas rectangle objects.............................................................................................34 7.14. Canvas text objects.....................................................................................................35 7.15. Canvas window objects..............................................................................................36 8. The Checkbutton widget......................................................................................................37 9. The Entry widget..................................................................................................................40 9.1. Scrolling an Entry widget............................................................................................43 10. The Frame widget................................................................................................................43 11. The Label widget................................................................................................................44 12. The LabelFrame widget......................................................................................................46 13. The Listbox widget............................................................................................................48 13.1. Scrolling a Listbox widget........................................................................................52 14. The Menu widget..................................................................................................................52 14.1. Menu item creation (coption) options.........................................................................55 14.2. Top-level menus.........................................................................................................56 15. The Menubutton widget......................................................................................................57 16. The Message widget............................................................................................................59 17. The OptionMenu widget.......................................................................................................60 18. The PanedWindow widget....................................................................................................61 18.1. PanedWindow child configuration options...................................................................63 19. The Radiobutton widget....................................................................................................64 20. The Scale widget................................................................................................................67 21. The Scrollbar widget........................................................................................................70 21.1. The Scrollbarcommand callback............................................................................72 21.2. Connecting a Scrollbar to another widget................................................................73 22. The Spinbox widget............................................................................................................73 23. The Text widget..................................................................................................................78 23.1. Text widget indices...................................................................................................80 23.2. Text widget marks....................................................................................................81 23.3. Text widget images...................................................................................................82 23.4. Text widget windows...............................................................................................82 23.5. Text widget tags.......................................................................................................82 23.6. Setting tabs in a Text widget......................................................................................83 23.7. The Text widget undo/redo stack..............................................................................83 23.8. Methods on Text widgets..........................................................................................84 24. Toplevel: Top-level window methods..................................................................................91 25. Universal widget methods.....................................................................................................93 26. Standardizing appearance...................................................................................................101 26.1. How to name a widget class......................................................................................102 26.2. How to name a widget instance.................................................................................102 26.3. Resource specification lines.......................................................................................102 26.4. Rules for resource matching......................................................................................103 27. Connecting your application logic to the widgets...................................................................104 28. Control variables: the values behind the widgets...................................................................104 29. Focus: routing keyboard input.............................................................................................106 New Mexico Tech Computer Center Tkinter reference 2 30. Events................................................................................................................................107 30.1. Levels of binding......................................................................................................108 30.2. Event sequences.......................................................................................................109 30.3. Event types..............................................................................................................109 30.4. Event modifiers........................................................................................................110 30.5. Key names...............................................................................................................111 30.6. Writing your handler: The Event class......................................................................113 30.7. The extra arguments trick..........................................................................................115 30.8. Virtual events...........................................................................................................116 31. Pop-up dialogs....................................................................................................................116 31.1. The tkMessageBox dialogs module..........................................................................116 31.2. The tkFileDialog module.....................................................................................118 31.3. The tkColorChooser module.................................................................................119
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值