Python Tkinter 自定义主题

Python Tkinter custom themes

描述

我想使用 Tkinter / ttk 和 python 制作一个 GUI,原因是我想学习设计 GUI 的样式。

我试图找到有关如何为 "Entry box" 设置样式的信息,而不是背景,而是实际的 "insert box",但我找不到有关如何设置样式的任何信息,而且内置主题非常好隐藏得很好因为我也找不到那些..

图片演示:


我的问题

是的,可以,您可以制作默认主题并将这些主题分配给小部件。您正在寻找的是 Style 选项。

我从中学到了几乎所有我需要知道的关于样式的知识: https://docs.python.org/3/library/tkinter.ttk.html#tkinter.ttk.Style

这里有一个小例子,可以让您了解基本概念

import tkinter
from tkinter import ttk

root = tkinter.Tk()
ttk.Style().configure("Blue.TEntry", background="blue")

blue_ent= ttk.Entry(text="Test", style="Blue.TEntry").pack()

root.mainloop()

这也很好地描述了如何使用 ttk.Style()http://www.tkdocs.com/tutorial/styles.html

The standard style applied to ttk.Entry simply doesn't take a fieldbackground option, which would be what changes the colour of the text entry field. The solution is this to create a new element that does respond to the option.

from tkinter import *
from tkinter import ttk

root_window = Tk()

estyle = ttk.Style()
estyle.element_create("plain.field", "from", "clam")
estyle.layout("EntryStyle.TEntry",
                   [('Entry.plain.field', {'children': [(
                       'Entry.background', {'children': [(
                           'Entry.padding', {'children': [(
                               'Entry.textarea', {'sticky': 'nswe'})],
                      'sticky': 'nswe'})], 'sticky': 'nswe'})],
                      'border':'2', 'sticky': 'nswe'})])

estyle.configure("EntryStyle.TEntry",
    fieldbackground="light blue")           # Set color here

entry = ttk.Entry(root_window, style="EntryStyle.TEntry")
entry.pack(padx=10, pady=10)

root_window.mainloop()
import tkinter
from tkinter import ttk

root = tkinter.Tk()
estyle = ttk.Style()
estyle.configure("Blue.TEntry", background="blue", fieldbackground="light blue")
estyle.layout("Blue.TEntry",
                   [('Entry.plain.field', {'children': [(
                       'Entry.background', {'children': [(
                           'Entry.padding', {'children': [(
                               'Entry.textarea', {'sticky': 'nswe'})],
                      'sticky': 'nswe'})], 'sticky': 'nswe'})],
                      'border':'2', 'sticky': 'nswe'})])
blue_ent= ttk.Entry(text="Test", style="Blue.TEntry")
blue_ent.pack()

root.mainloop()