Python Tkinter custom themes

心已入冬 提交于 2021-01-21 10:52:25

问题


Description

I want to make a GUI using Tkinter / ttk with python, the reason is because I want to learn to style GUI's.

I have tried to find information about how to style the "Entry box" not the background but the actual "insert box" but I cant find any information about how to do this and the built in themes is quite well hidden because I cant find those either..

Image demonstration:

  • Default Style

  • How I want it


My questions

  • Is this even possible and if so, how?
  • And is there a way to access the default themes in order to learn from them?

回答1:


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()



回答2:


Yes, it is possible, you can make your default themes and assign the widgets these themes. What you're looking for is the Style option.

I learnt pretty much everything I needed to know about styles from this : https://docs.python.org/3/library/tkinter.ttk.html#tkinter.ttk.Style

Here's a small example that should give you the basic idea

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()

This gives a good description of how to use ttk.Style() aswell: http://www.tkdocs.com/tutorial/styles.html



来源:https://stackoverflow.com/questions/37406575/python-tkinter-custom-themes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!