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",     #设置主题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

  • 31
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ftzchina

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值