ttkbootstrap界面美化系列之主窗口(二)

news2024/10/6 4:12:00

一:创建主窗口

在利用ttkbootstrap构建应用程序时,可以用tkinter传统的tk方法来创建主界面,也可以用ttkbootstrap中的window类来创建,下面我们来看看两者的区别

1,传统方法创建主界面

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

root = tk.Tk()
root.title('主窗口')
root.geometry('300x200')

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)

root.mainloop()

2,新方法创建主界面

import ttkbootstrap as ttk
from ttkbootstrap.constants import *

root = ttk.Window( title="主窗口",            #设置窗口的标题
                   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)

root.mainloop()

        从上面的运行界面上看,差异可能看起来很小,但正如您将看到的,Window类使用参数来设置许多属性和质量,而这些属性和质量只能在使用Tk类时使用方法进行设置。此外,Style对象会自动附加到Window对象。

二:window类的属性

可以用以下方法来获取window类的所有属性

print(dir(ttk.Window))

['_Misc__winfo_getint', '_Misc__winfo_parseitem', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattr__', '__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', '_getboolean', '_getconfigure', '_getconfigure1', '_getdoubles', '_getints', '_grid_configure', '_gridconvvalue', '_last_child_ids', '_loadtk', '_nametowidget', '_noarg_', '_options', '_register', '_report_exception', '_root', '_subst_format', '_subst_format_str', '_substitute', '_tclCommands', '_unbind', '_w', '_windowingsystem', 'after', 'after_cancel', 'after_idle', 'anchor', 'aspect', 'attributes', 'bbox', 'bell', 'bind', 'bind_all', 'bind_class', 'bindtags', 'cget', 'client', 'clipboard_append', 'clipboard_clear', 'clipboard_get', 'colormapwindows', 'columnconfigure', 'command', 'config', 'configure', 'deiconify', 'deletecommand', 'destroy', 'event_add', 'event_delete', 'event_generate', 'event_info', 'focus', 'focus_displayof', 'focus_force', 'focus_get', 'focus_lastfor', 'focus_set', 'focusmodel', 'forget', 'frame', 'geometry', 'getboolean', 'getdouble', 'getint', 'getvar', 'grab_current', 'grab_release', 'grab_set', 'grab_set_global', 'grab_status', 'grid', 'grid_anchor', 'grid_bbox', 'grid_columnconfigure', 'grid_location', 'grid_propagate', 'grid_rowconfigure', 'grid_size', 'grid_slaves', 'group', 'iconbitmap', 'iconify', 'iconmask', 'iconname', 'iconphoto', 'iconposition', 'iconwindow', 'image_names', 'image_types', 'info_patchlevel', 'keys', 'lift', 'loadtk', 'lower', 'mainloop', 'manage', 'maxsize', 'minsize', 'nametowidget', 'option_add', 'option_clear', 'option_get', 'option_readfile', 'overrideredirect', 'pack_propagate', 'pack_slaves', 'place_slaves', 'place_window_center', 'position_center', 'positionfrom', 'propagate', 'protocol', 'quit', 'readprofile', 'register', 'report_callback_exception', 'resizable', 'rowconfigure', 'selection_clear', 'selection_get', 'selection_handle', 'selection_own', 'selection_own_get', 'send', 'setvar', 'size', 'sizefrom', 'slaves', 'state', 'style', 'title', 'tk_bisque', 'tk_focusFollowsMouse', 'tk_focusNext', 'tk_focusPrev', 'tk_setPalette', 'tk_strictMotif', 'tkraise', 'transient', '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', 'withdraw', 'wm_aspect', 'wm_attributes', 'wm_client', 'wm_colormapwindows', 'wm_command', 'wm_deiconify', 'wm_focusmodel', 'wm_forget', 'wm_frame', 'wm_geometry', 'wm_grid', 'wm_group', 'wm_iconbitmap', 'wm_iconify', 'wm_iconmask', 'wm_iconname', 'wm_iconphoto', 'wm_iconposition', 'wm_iconwindow', 'wm_manage', 'wm_maxsize', 'wm_minsize', 'wm_overrideredirect', 'wm_positionfrom', 'wm_protocol', 'wm_resizable', 'wm_sizefrom', 'wm_state', 'wm_title', 'wm_transient', 'wm_withdraw']

 具体方法怎么使用可以用help来查看

print(help(ttk.Window))
class Window(tkinter.Tk)
 |  Window(title='ttkbootstrap', themename='litera', iconphoto='', size=None, position=None, minsize=None, maxsize=None, resizable=None, hdpi=True, scaling=None, transient=None, overrideredirect=False, alpha=1.0)
 |
 |  A class that wraps the tkinter.Tk class in order to provide a
 |  more convenient api with additional bells and whistles. For more
 |  information on how to use the inherited `Tk` methods, see the
 |  [tcl/tk documentation](https://tcl.tk/man/tcl8.6/TkCmd/wm.htm)
 |  and the [Python documentation](https://docs.python.org/3/library/tkinter.html#tkinter.Tk).
 |
 |  ![](../../assets/window/window-toplevel.png)
 |
 |  Examples:
 |
 |      ```python
 |      app = Window(title="My Application", themename="superhero")
 |      app.mainloop()
 |      ```
 |
 |  Method resolution order:
 |      Window
 |      tkinter.Tk
 |      tkinter.Misc
 |      tkinter.Wm
 |      builtins.object
 |
 |  Methods defined here:
 |
 |  __init__(self, title='ttkbootstrap', themename='litera', iconphoto='', size=None, position=None, minsize=None, maxsize=None, resizable=None, hdpi=True, scaling=None, transient=None, overrideredirect=False, alpha=1.0)
 |      Parameters:
 |
 |          title (str):
 |              The title that appears on the application titlebar.
 |
 |          themename (str):
 |              The name of the ttkbootstrap theme to apply to the
 |              application.
 |
 |          iconphoto (str):
 |              A path to the image used for the titlebar icon.
 |              Internally this is passed to the `Tk.iconphoto` method
 |              and the image will be the default icon for all windows.
 |              A ttkbootstrap image is used by default. To disable
 |              this default behavior, set the value to `None` and use
 |              the `Tk.iconphoto` or `Tk.iconbitmap` methods directly.
 |
 |          size (Tuple[int, int]):
 |              The width and height of the application window.
 |              Internally, this argument is passed to the
 |              `Window.geometry` method.
 |
 |          position (Tuple[int, int]):
 |              The horizontal and vertical position of the window on
 |              the screen relative to the top-left coordinate.
 |              Internally this is passed to the `Window.geometry`
 |              method.
 |
 |          minsize (Tuple[int, int]):
 |              Specifies the minimum permissible dimensions for the
 |              window. Internally, this argument is passed to the
 |              `Window.minsize` method.
 |
 |          maxsize (Tuple[int, int]):
 |              Specifies the maximum permissible dimensions for the
 |              window. Internally, this argument is passed to the
 |              `Window.maxsize` method.
 |
 |          resizable (Tuple[bool, bool]):
 |              Specifies whether the user may interactively resize the
 |              toplevel window. Must pass in two arguments that specify
 |              this flag for _horizontal_ and _vertical_ dimensions.
 |              This can be adjusted after the window is created by using
 |              the `Window.resizable` method.
 |
 |          hdpi (bool):
 |              Enable high-dpi support for Windows OS. This option is
 |              enabled by default.
 |
 |          scaling (float):
 |              Sets the current scaling factor used by Tk to convert
 |              between physical units (for example, points, inches, or
 |              millimeters) and pixels. The number argument is a
 |              floating point number that specifies the number of pixels
 |              per point on window's display.
 |
 |          transient (Union[Tk, Widget]):
 |              Instructs the window manager that this widget is
 |              transient with regard to the widget master. Internally
 |              this is passed to the `Window.transient` method.
 |
 |          overrideredirect (bool):
 |              Instructs the window manager to ignore this widget if
 |              True. Internally, this argument is passed to the
 |              `Window.overrideredirect(1)` method.
 |
 |          alpha (float):
 |              On Windows, specifies the alpha transparency level of the
 |              toplevel. Where not supported, alpha remains at 1.0. Internally,
 |              this is processed as `Toplevel.attributes('-alpha', alpha)`.
 |
 |  place_window_center(self)
 |      Position the toplevel in the center of the screen. Does not
 |      account for titlebar height.
 |
 |  position_center = place_window_center(self)

下面给出常用的参数配置示例:

root = ttk.Window(  title="主窗口",        #设置窗口的标题
			        themename="yeti",     #设置主题yeti
			        size=(300,200),        #窗口的大小
			        position=(200,100),     #窗口所在的位置
			        minsize=(0,0),          #窗口的最小宽高
			        maxsize=(1920,1080),    #窗口的最大宽高
			        resizable=None,         #设置窗口是否可以更改大小
			        alpha=1.0,              #设置窗口的透明度(0.0完全透明)
                 )

root.place_window_center()    #让显现出的窗口居中
root.resizable(False,False)   #让窗口不可更改大小
root.wm_attributes('-topmost', 1)#让窗口位置其它窗口之上
root.iconbitmap(get_path("ico/zrt.ico"))

官方文档:Window - ttkbootstrap 

三:界面主题

在上面的示例中可以通过themename参数来设置主题,在ttkbootstrap中有很多已经设置好的主题供开发者使用,但是具体有哪些主题呢,可以通过下面的方法来获取

from ttkbootstrap.style import Style

# instantiate the style with default theme
style = Style()

# instantiate the style with another theme
style = Style(theme='superhero')

# check all available themes
for theme in style.theme_names():
    print(theme)

以下是内置支持的主题: 

cosmo
flatly
litera
minty
lumen
sandstone
yeti
pulse
united
morph
journal
darkly
superhero
solar
cyborg
vapor
simplex
cerculean

官方文档给出了每种主题的样式,大家可以根据自己的审美选择合适的主题

Themes — ttkbootstrap documentation

主题 - ttkbootstrap

下面给出几张官方样例:

 

 

 四:小组件主题

除了上面对整体界面进行主题设置,也可以单独对某个小部件的主题进行设置,如设置按钮的颜色

import ttkbootstrap as ttk
from ttkbootstrap.constants import *

root = ttk.Window()

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

root.mainloop()

以下是支持内置颜色:

primary
secondary
success
info
warning
danger
light
dark

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

力扣思路题:最长特殊序列1

int findLUSlength(char * a, char * b){int alenstrlen(a),blenstrlen(b);if (strcmp(a,b)0)return -1;return alen>blen?alen:blen; }

[CVPR-24] Text-to-3D using Gaussian Splatting

3DGS对初始化敏感;引入基于Point-E的3D SDS可以缓解多脸问题;外观细化阶段可以有效抑制异常点,并提高可视化效果;不需要对SDS的改进,用gudiance scale100可以取得很不错的结果。 [pdf | proj | code] 方法 Geometry O…

Linux——动静态库的制作及使用与动态库原理

目录 一、静态库 1.静态库的制作 2.静态库的使用 加载静态库方法一:安装头文件与库文件 加载静态库方法二:指定文件目录 二、动态库 1.动态库的制作 2.动态库的使用 方法一:安装到系统中 方法二:软链接 方法三&…

c语言文件操作(中)

目录 1. 文件的顺序读写1.1 顺序读写函数1.2 顺序读写函数的原型和介绍 结语 1. 文件的顺序读写 1.1 顺序读写函数 函数名功能适用于fgetc字符输入函数所有输出流fputc字符输出函数所有输出流fgets文本行输入函数所有输出流fputs文本行输出函数所有输出流fscanf格式化输入函数…

刷题DAY24 | LeetCode 77-组合

1 回溯法理论基础 回溯法也可以叫做回溯搜索法,它是一种搜索的方式。回溯是递归的副产品,只要有递归就会有回溯。 所以以下讲解中,回溯函数也就是递归函数,指的都是一个函数。 1.1 回溯法的效率 回溯法的性能如何呢&#xff0…

完整指南:如何使用 Stable Diffusion API

Stable Diffusion 是一个先进的深度学习模型,用于创造和修改图像。这个模型能够基于文本描述来生成图像,让机器理解和实现用户的创意。使用这项技术的关键在于掌握其 API,通过编程来操控图像生成的过程。 在探索 Stable Diffusion API 的世界…

HarmonyOS NEXT应用开发之Web获取相机拍照图片案例

介绍 本示例介绍如何在HTML页面中拉起原生相机进行拍照,并获取返回的图片。 效果预览图 使用说明 点击HTML页面中的选择文件按钮,拉起原生相机进行拍照。完成拍照后,将图片在HTML的img标签中显示。 实现思路 添加Web组件,设置…

Vue.js+SpringBoot开发食品生产管理系统

目录 一、摘要1.1 项目介绍1.2 项目录屏 二、功能模块2.1 加工厂管理模块2.2 客户管理模块2.3 食品管理模块2.4 生产销售订单管理模块2.5 系统管理模块2.6 其他管理模块 三、系统展示四、核心代码4.1 查询食品4.2 查询加工厂4.3 新增生产订单4.4 新增销售订单4.5 查询客户 五、…

生成式人工智能服务安全基本要求实务解析

本文尝试明晰《基本要求》的出台背景与实践定位,梳理《基本要求》所涉的各类安全要求,以便为相关企业遵循执行《基本要求》提供抓手。 引言 自2022年初以来,我国陆续发布算法推荐、深度合成与生成式人工智能服务相关的规范文件,…

阿里云服务器ECS经济型e实例性能如何?

阿里云服务器ECS推出经济型e系列,经济型e实例是阿里云面向个人开发者、学生、小微企业,在中小型网站建设、开发测试、轻量级应用等场景推出的全新入门级云服务器,CPU采用Intel Xeon Platinum架构处理器,支持1:1、1:2、1:4多种处理…

JS第一阶段1

文章目录 1. js组成2. JS三种书写位置JS输出语句 3. 变量4. 数据类型Number字符串型 String布尔型booleanUnddefined和Null 5. 获取变量的数据类型获取检测变量的数据类型 6. 数据转换类型转换为字符串转换为数字型(重点)转换为布尔型 7.运算符算数运算符…

找不到msvcp110.dll怎么办,msvcp110.dll丢失的5种修复方法

在计算机使用过程中,我们经常会遇到一些错误提示,其中之一就是“msvcp110.dll丢失”。由于msvcp110.dll是Microsoft Visual C Redistributable Package的重要组成部分,它的缺失会导致依赖于该组件的软件无法正常启动或运行,比如某…

从初学者到专家:Java反射的完整指南

一.反射的概念及定义 Java 的反射( reflection )机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意方法和属性,既然能拿到那么&#x…

Jenkins + Docker + ASP.NET Core自动化部署

本来没想着要写这篇博客,但是在实操过程中,一个是被网络问题搞炸了心态(真心感觉网络能把人搞疯,别人下个包、下个镜像几秒钟搞定,我看着我的几KB小水管真是有苦说不出),另一个就是这里面坑还是…

C语言---指针的两个运算符:点和箭头

目录 点(.)运算符箭头(->)运算符需要注意实际例子 C语言中的指针是一种特殊的变量,它存储了一个内存地址。点(.)和箭头(->)是用于访问结构体和联合体成员的运算符。…

手撕算法-二叉树的镜像

题目描述 操作给定的二叉树,将其变换为源二叉树的镜像。数据范围:二叉树的节点数 0≤_n_≤1000 , 二叉树每个节点的值 0≤_val_≤1000要求: 空间复杂度 O(n) 。本题也有原地操作,即空间复杂度 O(1) 的解法&#xff0c…

【设计模式】-工厂模式

工厂模式是一种创建型设计模式,它提供了一种在不指定具体类的情况下创建对象的方法。工厂模式的核心思想是将对象的创建与使用分离,降低系统的耦合度,使系统更加灵活、可扩展。 工厂模式主要分为三种类型:简单工厂模式、工厂方法…

苍穹外卖-day06:HttpClient、微信小程序开发、微信登录(业务流程)、导入商品浏览功能代码(业务逻辑)

苍穹外卖-day06 课程内容 HttpClient微信小程序开发微信登录导入商品浏览功能代码 功能实现:微信登录、商品浏览 微信登录效果图: 商品浏览效果图: 1. HttpClient 1.1 介绍 HttpClient 是Apache Jakarta Common 下的子项目,…

苍穹外卖-day04:项目实战-套餐管理(新增套餐,分页查询套餐,删除套餐,修改套餐,起售停售套餐)业务类似于菜品模块

苍穹外卖-day04 课程内容 新增套餐套餐分页查询删除套餐修改套餐起售停售套餐 要求: 根据产品原型进行需求分析,分析出业务规则设计接口梳理表之间的关系(分类表、菜品表、套餐表、口味表、套餐菜品关系表)根据接口设计进行代…

C#重新认识笔记_ 点乘,叉乘

C#重新认识笔记_ 点积,叉乘 一、Dot Product 点乘: (Ax*Bx)(Ay*By)(Az*Bz)Dot Product 点积 利用点积,可以了解,两个向量(vector)的相关信息, …