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

一:创建主窗口

在利用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",     #设置主题yetisize=(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.hqwc.cn/news/548791.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

AI论文速读 | UniST:提示赋能通用模型用于城市时空预测

本文是时空领域的统一模型——UniST,无独有偶,时序有个统一模型新工作——UniTS,感兴趣的读者也可以阅读今天发布的另外一条。 论文标题:UniST: A Prompt-Empowered Universal Model for Urban Spatio-Temporal Prediction 作者&…

C++——字符串、读写文件、结构体、枚举

个人简介 👀个人主页: 前端杂货铺 🙋‍♂️学习方向: 主攻前端方向,正逐渐往全干发展 📃个人状态: 研发工程师,现效力于中国工业软件事业 🚀人生格言: 积跬步…

兼顾稳定和性价比的跨国企业SD-WAN组网

随着全球业务不断扩张,跨国企业面临着跨域网络的复杂性和不稳定性带来的挑战。不同地区分支机构的数据互通和协作常常受到制约,而在网络问题出现后,排查多方问题导致高昂的部署和运维成本。尽管直连方案在表面上看似省钱,但由于不…

【Selenium(一)】

简介 Selenium是一个开源的自动化测试工具,主要用于Web应用程序的自动化测试。它支持多种浏览器,包括Chrome、Firefox、Internet Explorer等,以及多种编程语言,如Java、Python、C#、Ruby等,使得它成为Web自动化测试中…

LeetCode 热题 100

未完待续… 一、哈希 1、两数之和 # 暴力解,时间复杂度:o(n^2) class Solution(object):def twoSum(self, nums, target):""":type nums: List[int]:type target: int:rtype: List[int]"""for i in range(len(nums)):fo…

【高通camera hal bug分析】高通自带相机镜像问题

首先打了两个log,一个是开启镜像的log,还有一个是没有开启镜像的log,如果我们开启镜像以后,观察开启镜像log发现 , 这段代码走的没有任何问题,因为Flip的值等于1了。 关闭镜像log如下: 如果我们不开启镜像…

2024-3-18 市场情绪高潮

竞价最大亮点就是 永悦科技 顶一字超预期,上周五带动了低空经济板块,今天直接一字走加速,pk掉了同身位的 大理药业,把 艾艾精工 的强分歧也顶回去了,所以核心是 永悦科技,题材上 设备更新的废固处理继续&am…

【全网最详细】ComfyUI下,Insightface安装指南-聚梦小课堂

🥮背景 ComfyUI下使用IP-adapter下的faceID模型的时候,大家可能会遇到如下错误: Error occurred when executing InsightFaceLoader: No module named insightface File "F:\ComfyUI-aki\execution.py", line 151, in recursive_…

浅谈如何自我实现一个消息队列服务器(2)——细节详解

文章目录 一、实现 broker server 服务器1.1 创建一个SpringBoot项目1.2 创建Java类 二、硬盘持久化存储 broker server 里的数据2.1 数据库存储2.1.1 浅谈SQLiteMyBatis 2.1.2 如何使用SQLite 2.2 文件存储 三、将broker server 里的数据存储在内存上四、使用DataBaseManager类…

java 线上生产问题排查思路,jvm内存溢出实例重启原因排查生产实战

java jvm内存溢出实例重启排查生产实战(使用VisualVM) 背景 项目组线上生产环境不定期的发生内存爆满然后实例重启,实例发布上线后实例内存不断增长最后维持在百分之九十多,十分危险。因此我参与到了排查中,本篇博客将…

TTS 擂台: 文本转语音模型的自由搏击场

对文本转语音 (text-to-speech, TTS) 模型的质量进行自动度量非常困难。虽然评估声音的自然度和语调变化对人类来说是一项微不足道的任务,但对人工智能来说要困难得多。为了推进这一领域的发展,我们很高兴推出 TTS 擂台。其灵感来自于LMSys为 LLM 提供的…

08|记忆:通过Memory记住客户上次买花时的对话细节

无论是LLM还是代理都是无状态的,每次模型的调用都是独立于其他交互的。也就是说,我们每次通过API开始和大语言模型展开一次新的对话,它都不知道你其实昨天或者前天曾经和它聊过天了。 使用ConversationChain from langchain import OpenAI…