ttkbootstrap界面美化系列之按钮Button(三)

目录

一:Button接口

二:Button创建

三:Button主题

四:Button样式

五:Button状态


        从本章开始将详细介绍ttkbootstrap中支持的常用组件,从按钮BUTTON开始,在各类界面设计中按钮几乎是必不可少的一个组件。

一:Button接口

查看Button的接口可以通过help来看

print(help(ttk.Button))
Help on class Button in module tkinter.ttk:

class Button(Widget)
 |  Button(*args, **kwargs)
 |
 |  Ttk Button widget, displays a textual label and/or image, and
 |  evaluates a command when pressed.
 |
 |  Method resolution order:
 |      Button
 |      Widget
 |      tkinter.Widget
 |      tkinter.BaseWidget
 |      tkinter.Misc
 |      tkinter.Pack
 |      tkinter.Place
 |      tkinter.Grid
 |      builtins.object
 |
 |  Methods defined here:
 |
 |  __init__(self, *args, **kwargs)
 |
 |  config = configure(self, cnf=None, **kwargs)
 |
 |  configure(self, cnf=None, **kwargs)
 |
 |  invoke(self)
 |      Invokes the command associated with the button.
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from Widget:
 |
 |  identify(self, x, y)
 |      Returns the name of the element at position x, y, or the empty
 |      string if the point does not lie within any element.
 |
 |      x and y are pixel coordinates relative to the widget.
 |
 |  instate(self, statespec, callback=None, *args, **kw)
 |      Test the widget's state.
 |
 |      If callback is not specified, returns True if the widget state
 |      matches statespec and False otherwise. If callback is specified,
 |      then it will be invoked with *args, **kw if the widget state
 |      matches statespec. statespec is expected to be a sequence.
 |
 |  state(self, statespec=None)
 |      Modify or inquire widget state.
 |
 |      Widget state is returned if statespec is None, otherwise it is
 |      set according to the statespec flags and then a new state spec
 |      is returned indicating which flags were changed. statespec is
 |      expected to be a sequence.
 |
 |  ----------------------------------------------------------------------
 |  Methods inherited from tkinter.BaseWidget:
 |
 |  destroy(self)
 |      Destroy this and all descendants widgets.
 |
...
...
...

通过dir来查看穿件Button后支持的属性和方法

['_Misc__winfo_getint', '_Misc__winfo_parseitem', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_bind', '_configure', '_displayof', '_do', '_getboolean', '_getconfigure', '_getconfigure1', '_getdoubles', '_getints', '_grid_configure', '_gridconvvalue', '_last_child_ids', '_nametowidget', '_noarg_', '_options', '_register', '_report_exception', '_root', '_setup', '_subst_format', '_subst_format_str', '_substitute', '_tclCommands', '_unbind', '_windowingsystem', 'after', 'after_cancel', 'after_idle', 'anchor', 'bbox', 'bell', 'bind', 'bind_all', 'bind_class', 'bindtags', 'cget', 'clipboard_append', 'clipboard_clear', 'clipboard_get', 'columnconfigure', 'config', 'configure', 'deletecommand', 'destroy', 'event_add', 'event_delete', 'event_generate', 'event_info', 'focus', 'focus_displayof', 'focus_force', 'focus_get', 'focus_lastfor', 'focus_set', 'forget', 'getboolean', 'getdouble', 'getint', 'getvar', 'grab_current', 'grab_release', 'grab_set', 'grab_set_global', 'grab_status', 'grid', 'grid_anchor', 'grid_bbox', 'grid_columnconfigure', 'grid_configure', 'grid_forget', 'grid_info', 'grid_location', 'grid_propagate', 'grid_remove', 'grid_rowconfigure', 'grid_size', 'grid_slaves', 'identify', 'image_names', 'image_types', 'info', 'info_patchlevel', 'instate', 'invoke', 'keys', 'lift', 'location', 'lower', 'mainloop', 'nametowidget', 'option_add', 'option_clear', 'option_get', 'option_readfile', 'pack', 'pack_configure', 'pack_forget', 'pack_info', 'pack_propagate', 'pack_slaves', 'place', 'place_configure', 'place_forget', 'place_info', 'place_slaves', 'propagate', 'quit', 'register', 'rowconfigure', 'selection_clear', 'selection_get', 'selection_handle', 'selection_own', 'selection_own_get', 'send', 'setvar', 'size', 'slaves', 'state', 'tk_bisque', 'tk_focusFollowsMouse', 'tk_focusNext', 'tk_focusPrev', 'tk_setPalette', 'tk_strictMotif', 'tkraise', 'unbind', 'unbind_all', 'unbind_class', 'update', 'update_idletasks', 'wait_variable', 'wait_visibility', 'wait_window', 'waitvar', 'winfo_atom', 'winfo_atomname', 'winfo_cells', 'winfo_children', 'winfo_class', 'winfo_colormapfull', 'winfo_containing', 'winfo_depth', 'winfo_exists', 'winfo_fpixels', 'winfo_geometry', 'winfo_height', 'winfo_id', 'winfo_interps', 'winfo_ismapped', 'winfo_manager', 'winfo_name', 'winfo_parent', 'winfo_pathname', 'winfo_pixels', 'winfo_pointerx', 'winfo_pointerxy', 'winfo_pointery', 'winfo_reqheight', 'winfo_reqwidth', 'winfo_rgb', 'winfo_rootx', 'winfo_rooty', 'winfo_screen', 'winfo_screencells', 'winfo_screendepth', 'winfo_screenheight', 'winfo_screenmmheight', 'winfo_screenmmwidth', 'winfo_screenvisual', 'winfo_screenwidth', 'winfo_server', 'winfo_toplevel', 'winfo_viewable', 'winfo_visual', 'winfo_visualid', 'winfo_visualsavailable', 'winfo_vrootheight', 'winfo_vrootwidth', 'winfo_vrootx', 'winfo_vrooty', 'winfo_width', 'winfo_x', 'winfo_y']

二:Button创建

先来看一个简单示例

import tkinter as tk
import ttkbootstrap as ttk
from ttkbootstrap.constants import *

root = ttk.Window(  title="主窗口",        #设置窗口的标题
                    themename="yeti",     #设置主题yeti
                    size=(300,200),        #窗口的大小
                 )

b1 = ttk.Button(root, text="Button 1", bootstyle=SUCCESS)
b1.pack(side=LEFT, padx=5, pady=10)

b2 = ttk.Button(root, text="Button 2", bootstyle=(INFO, OUTLINE))
b2.pack(side=LEFT, padx=5, pady=10)

b3=tk.Button(root,text="Button 3")
b3.pack(side=LEFT, padx=5, pady=10)

root.mainloop()

上面例子中,我们分别用ttk和tk新老两个方法来创建了按钮,有些初接触的同学可能有些好奇,Button都支持哪些参数些,可以通过keys方法来查看,为了便于比较我们将新老两种的参数都打印出来

ttk.button的参数如下:

['command', 'default', 'takefocus', 'text', 'textvariable', 'underline', 'width', 'image', 'compound', 'padding', 'state', 'cursor', 'style', 'class']

tk.button的参数如下:

['activebackground', 'activeforeground', 'anchor', 'background', 'bd', 'bg', 'bitmap', 'borderwidth', 'command', 'compound', 'cursor', 'default', 'disabledforeground', 'fg', 'font', 'foreground', 'height', 'highlightbackground', 'highlightcolor', 'highlightthickness', 'image', 'justify', 'overrelief', 'padx', 'pady', 'relief', 'repeatdelay', 'repeatinterval', 'state', 'takefocus', 'text', 'textvariable', 'underline', 'width', 'wraplength']

从上面可以看到ttk.button的参数比tk.button少了很多,是不是意味着这些老的参数设置在新的里面就不支持了呢,其实并不是的,老的很多参数设置可以在style中设置,在官方文档中也详细描述了参数的前后兼容情况

官方文档:29. ttk.Button

Table 35. ttk.Button options

class_The widget class name. This may be specified when the widget is created, but cannot be changed later. For an explanation of widget classes, see Section 27, “Standardizing appearance”.
commandA function to be called when the button is pressed.
compound

If you provide both image and text options, the compound option specifies the position of the image relative to the text. The value may be tk.TOP (image above text), tk.BOTTOM (image below text), tk.LEFT (image to the left of the text), or tk.RIGHT (image to the right of the text).

When you provide both image and text options but don't specify a compound option, the image will appear and the text will not.

cursorThe cursor that will appear when the mouse is over the button; see Section 5.8, “Cursors”.
imageAn image to appear on the button; see Section 5.9, “Images”.
styleThe style to be used in rendering this button; see Section 49, “Using and customizing ttk styles”.
takefocusBy default, a ttk.Button will be included in focus traversal; see Section 53, “Focus: routing keyboard input”. To remove the widget from focus traversal, use takefocus=False.
textThe text to appear on the button, as a string.
textvariableA variable that controls the text that appears on the button; see Section 52, “Control variables: the values behind the widgets”.
underlineIf this option has a nonnegative value n, an underline will appear under the character at position n.
widthIf the label is text, this option specifies the absolute width of the text area on the button, as a number of characters; the actual width is that number multiplied by the average width of a character in the current font. For image labels, this option is ignored. The option may also be configured in a style.

These options of the Tkinter Button widget are not supported by the ttk.Button constructor:

Table 36. Tkinter Button options not in ttk.Button

activebackgroundUse a style map to control the background option; see Section 50.2, “ttk style maps: dynamic appearance changes”.
activeforegroundUse a style map to control the foreground option.
anchor

Configure this option using a style; see Section 49, “Using and customizing ttk styles”. Use this option to specify the position of the text when the width option allocates extra horizontal space.

For example, if you specify options width=20 and compound=tk.RIGHT on a button that displays both text and and image, and a style that specifies anchor=tk.E (east), the image will be at the right-hand end of the twenty-character space, with the text just to its left.

When the button displays an image but no text, this option is ignored.

background or bgConfigure the background option using a style. The bg abbreviation is not supported.
bitmapNot supported.
borderwidth or bdConfigure the borderwidth option using a style. The bd abbreviation is not supported.
cursorThe cursor that will appear when the mouse is over the checkbutton; see Section 5.8, “Cursors”.
defaultNot supported; see Section 50.2, “ttk style maps: dynamic appearance changes”.
disabledforegroundUse a style map for the foreground option; see Section 50.2, “ttk style maps: dynamic appearance changes”.
fontConfigure this option using a style.
foreground or fgConfigure this option using a style.
heightNot supported.
highlightbackgroundTo control the color of the focus highlight when the button does not have focus, use a style map to control the highlightcolor option; see Section 50.2, “ttk style maps: dynamic appearance changes”.
highlightcolorYou may specify the default focus highlight color by setting this option in a style. You may also control the focus highlight color using a style map.
highlightthicknessConfigure this option using a style. This option may not work in all themes.
justifyIf the text contains newline ('\n') characters, the text will occupy multiple lines on the button. The justify option controls how each line is positioned horizontally. Configure this option using a style; values may be tk.LEFTtk.CENTER, or tk.RIGHT for lines that are left-aligned, centered, or right-aligned, respectively.
overreliefUse a style map to control the relief option; see Section 50.2, “ttk style maps: dynamic appearance changes”.
padxNot supported.
padyNot supported.
reliefConfigure this option using a style; see Section 49, “Using and customizing ttk styles”.
repeatdelayNot supported.
repeatintervalNot supported.
stateIn ttk, there is no option with this name. The state mechanism has been generalized; see Section 50.2, “ttk style maps: dynamic appearance changes”.
wraplengthIf you use a style with this option set to some dimensions, the text will be sliced into pieces no longer than that dimension.

三:Button主题

Button如果不设置主题就会用默认的框架主题,如果在框架下想为Button设置单独的主题可以用style来设置

import tkinter as tk
import ttkbootstrap as ttk
from ttkbootstrap.constants import *

root = ttk.Window(  title="主窗口",        #设置窗口的标题
                    themename="yeti",     #设置主题yeti
                    size=(400,200),        #窗口的大小
                 )

style = ttk.Style()
style.configure('TButton', font=('宋体', 10))
style.map('TButton', font=[('active', ('宋体', 15))])#所有Button生效
style.configure('custom.TButton',  font=('宋体', 20),background='red')

b1 = ttk.Button(root, text="Button 1", bootstyle=SUCCESS)
b1.pack(side=LEFT, padx=5, pady=10)
print(b1.keys())

b2 = ttk.Button(root, text="Button 2", bootstyle=(INFO, OUTLINE))
b2.pack(side=LEFT, padx=5, pady=10)

b3 = ttk.Button(root, text="Button 2", style='custom.TButton')
b3.pack(side=LEFT, padx=5, pady=10)

root.mainloop()

需要注意的是configure中的‘custom.TButton’并不是随便命名的,点后边的组件是有要求,大部分样式名都在组件类名的前面加大写的T

官网:49. Using and customizing ttk styles

 另外图省事的话也可以通过bootstyle来设置,bootstyle的写法也是比较灵活的,下边的都是支持的

如何在已创建窗口下切换主题风格

import ttkbootstrap as ttk
from ttkbootstrap.constants import *

# 定义函数,与组合框相互结合,当组合框选中一条时,切换选中的主题
def select_theme(event):
    ttk.Style(theme_select_combo.get())

# 在创建窗口时
root = ttk.Window(themename="vapor")

# 定义框架(将标签和组合框并列在一行)
frame1 = ttk.Frame(root)
frame1.pack()

label = ttk.Label(frame1,text="主题选择:",font=15)
label.pack(side=LEFT)

# 主题选择组合框
var = ttk.StringVar()
theme_select_combo = ttk.Combobox(frame1,textvariable=var,values=["cosmo","flatly","minty","vapor"],bootstyle=SUCCESS)
theme_select_combo.bind("<<ComboboxSelected>>", select_theme) # 绑定事件
theme_select_combo.pack(side=LEFT,padx=10,pady=5)

for color in root.style.colors:
    btn = ttk.Button(root,text=color,bootstyle=color)
    btn.pack(side=LEFT,padx=5,pady=5)

root.mainloop()

 

四:Button样式

Button样式总共有三种

1,实心按钮:solid

2,外框按钮:outline

3,链接按钮:link

import tkinter as tk
import ttkbootstrap as ttk
from ttkbootstrap.constants import *

root = ttk.Window(  title="主窗口",        #设置窗口的标题
                    themename="yeti",     #设置主题yeti
                    size=(400,200),        #窗口的大小
                 )

b1 = ttk.Button(root, text="solid", bootstyle="info-solid")
b1.pack(side=LEFT, padx=5, pady=10)
print(b1.keys())

b2 = ttk.Button(root, text="outline", bootstyle="dark-outline")
b2.pack(side=LEFT, padx=5, pady=10)

b3 = ttk.Button(root, text="link", bootstyle="danger-link")
b3.pack(side=LEFT, padx=5, pady=10)

root.mainloop()

五:Button状态

 按钮一共有三大状态:

1,normal

2,active

3,disabled

以下两种方法均可以设置按钮状态

from ttkbootstrap.constants import *

root = ttk.Window(  title="主窗口",        #设置窗口的标题
                    themename="yeti",     #设置主题yeti
                    size=(400,200),        #窗口的大小
                 )

b1 = ttk.Button(root, text="solid", bootstyle="info-solid")
b1.pack(side=LEFT, padx=5, pady=10)
b1.configure(state="disabled")

b2 = ttk.Button(root, text="outline", bootstyle="dark-outline",state=DISABLED)
b2.pack(side=LEFT, padx=5, pady=10)


root.mainloop()

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/478868.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

解锁AI生成模型的无限可能:Stability-AI 带你领略前沿科技

厌倦了千篇一律的图片和视频&#xff1f;想要创作独一无二的艺术作品&#xff1f;Stability-AI 横空出世&#xff0c;为你打开通往 AI 生成模型的大门&#xff0c;带你领略前沿科技的无限可能&#xff01; 神奇的功能&#xff0c;尽在掌握 Stability-AI 拥有众多令人惊叹的功能…

第2讲-Memory(4)拓展

存储器芯片结构 存储器扩展 地址总线:这决定了处理器将从内存中读取数据或写入数据的内存位置。 数据总线:它包含已从内存位置读取或将写入内存位置的数据内容。 控制总线:它管理组件之间的信息流,指示操作是读取还是写入,并确保操作在正确的时间发生。

聊一下大模型的函数调用-Function call

你好&#xff0c;我是 shengjk1&#xff0c;多年大厂经验&#xff0c;努力构建 通俗易懂的、好玩的编程语言教程。 欢迎关注&#xff01;你会有如下收益&#xff1a; 了解大厂经验拥有和大厂相匹配的技术等 希望看什么&#xff0c;评论或者私信告诉我&#xff01; 文章目录 一…

Springboot 利用自定义注解+切面,实现 查询数据集合时主动加序列字段

利用自定义注解切面,实现 查询数据集合时主动加序列字段, 只需要在Dao接口&#xff0c;方法上引入注解即可 import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotat…

数据结构 - 链表

一.链表的概念 链表是一个在物理存储单元中不连续&#xff0c;没有顺序的的存储结构&#xff0c;关于它的顺序是由链表中的指针链接实现的&#xff0c;是一种递归的数据结构&#xff0c;链表有一系列节点组成&#xff0c;而这些节点会在运行时动态生成。 节点包括两个部分&am…

【docker】查看并拷贝容器内文件

一、查询容器 查询所有容器 docker ps查询名为os11的容器 docker ps | grep os11查询名为os11的容器&#xff08;包含不运行的&#xff09; docker ps -a| grep os11 docker ps [option] 显示结果介绍如下&#xff1a; 参考&#xff1a;[https://blog.51cto.com/u_15009374/31…

工厂投产、电池装车,广汽能上动力电池行业的“餐桌”吗?

文 | 智能相对论 作者 | 沈浪 “如果你不在餐桌上&#xff0c;你就会出现在菜单上。”在某种程度上&#xff0c;追逐效益的动力电池行业正在上演着布林肯的“餐桌菜单论”。 于是&#xff0c;我们可以看到&#xff0c;尽管整体的动力电池市场被宁德时代、比亚迪、LG新能源、…

怿星科技Neptune CHT-S测试系统,让智能座舱测试更加高效便捷

随着汽车“智能化”浪潮的推进&#xff0c;汽车的智能化水平正在持续刷新行业认知。在这股智能化潮流中&#xff0c;智能座舱作为客户体验最为直观的部分&#xff0c;其重要性不言而喻。倘若座舱设备出现死机、黑屏、卡顿等现象&#xff0c;都将对客户的使用体验产生非常大的影…

领军量子时代!逾九成机构加盟「英伟达」生态系统

在2024年3月17日至21日举行的GTC大会上&#xff0c;芯片制造领军企业英伟达&#xff08;NVIDIA&#xff09;发布了一项革命性的云服务&#xff0c;专为推动量子计算研究而设计。这一新服务&#xff0c;名为英伟达量子云&#xff08;NVIDIA Quantum Cloud&#xff09;&#xff0…

外包干了15天,技术退步明显。。。。。

先说一下自己的情况&#xff0c;本科生&#xff0c;2019年我通过校招踏入了南京一家软件公司&#xff0c;开始了我的职业生涯。那时的我&#xff0c;满怀热血和憧憬&#xff0c;期待着在这个行业中闯出一片天地。然而&#xff0c;随着时间的推移&#xff0c;我发现自己逐渐陷入…

C# winform修改背景图 控件双向绑定 拖拽打开图片

修改背景图 说明 这里我准备基于百度飞桨PaddleSeg项目的人像分割模块做一个人像抠图&#xff0c;这里顺便用上了双向绑定和图片拖拽打开。 下面就是示例&#xff1a; 用颜色替换 用背景图替换 保存成功后的图片 一、使用百度飞桨PaddleSeg //初始化 引擎engine new Padd…

掌握未来技术:国产openEuler 操作系统学习网站指南!

介绍&#xff1a;openEuler是一个开源的操作系统平台&#xff0c;由华为技术有限公司发起并维护。 首先&#xff0c;openEuler支持多种处理器架构&#xff0c;包括但不限于AArch64&#xff08;鲲鹏&#xff09;和x86-64&#xff0c;这使得它可以在多种硬件平台上运行&#xff0…

滴水逆向PE结构

1.操作系统是只能打开可执行文件 以4D 5A开头MZ 其他的txt都是什么wrod 都是在exe程序中打开的 txt啥的不是可执行文件 PE结构是分节的 一节一节 节省硬盘空间 32位中任何一个exe都有4g的虚拟内存 占内存空间大 给磁盘空间小 在硬盘空间紧密 在内存空间大 &#xff08…

设计模式 --4:工厂方法模式

总结 &#xff1a; 个人理解&#xff1a; 工厂方法模式就是在简单工程模式的基础下将工厂类抽象出来。如果不抽象工厂类 &#xff0c;每一次创建一个新的算法&#xff0c;都要修改原来的工厂类&#xff0c;这不符合 开放–封闭原则 将工厂类给抽象出来&#xff0c;让具体的算法…

appium自动化框架综合实践

结合前面的元素寻找、操作、unittest测试框架&#xff0c;搭建一个完整的自动化框架。本篇旨在框架设计、单机用例执行、输出报告&#xff0c;下篇继续实践Bat批处理执行测试、多设备并发测试。 框架功能 数据配置日志输出截图处理基础功能封装&#xff08;公共方法&#xff…

Java学习笔记NO.24

T1.完成理工超市系统的商品类及其子类的定义&#xff0c;实现“浏览商品”及“查看商品详情”功能 &#xff08;1&#xff09;商品类 public class Goods {public String name;public double price;public int count;public String desc;public Goods(String name, double p…

敏捷开发——第二次作业JS/服务器的部署

部署 Web 服务器 1. 安装 Apache HTTP 服务器并部署静态网页应用 ⭐⭐ 默认情况下&#xff0c;Apache 在 /var/www/html 目录下寻找要提供服务的文件。可以将静态网页文件放置在这个目录下 2.安装 Nginx 并部署静态页面应用 3. 实践部分 1. 2. 3. 在 /var/www/html 目录下…

用大语言模型控制交通信号灯,有效缓解拥堵!

城市交通拥堵是一个全球性的问题&#xff0c;在众多缓解交通拥堵的策略中&#xff0c;提高路口交通信号控制的效率至关重要。传统的基于规则的交通信号控制&#xff08;TSC&#xff09;方法&#xff0c;由于其静态的、基于规则的算法&#xff0c;无法完全适应城市交通不断变化的…

又一款代码神器,效率直接翻倍!免费的还是香啊!

前言 提到商汤科技&#xff0c;你可能仍然将其与“AI四小龙”、“计算机视觉领军企业”等标签联系在一起。然而&#xff0c;在ChatGPT与Sora赢得广泛关注后&#xff0c;商汤科技依托其深厚的人工智能技术基础&#xff0c;迅速开发出自己的大型模型及人工智能应用产品&#xff…

网络基础(一)初识

1、计算机网络背景 1.1、网络发展 1. 独立模式: 计算机之间相互独立&#xff1b; 2. 网络互联: 多台计算机连接在一起&#xff0c;完成数据共享&#xff1b; 3. 局域网LAN: 计算机数量更多了, 通过交换机和路由器连接在一起; 4. 广域网WAN: 将远隔千里的计算机都连在一起;…
最新文章