python - 如何在所有窗口中设置组合框的颜色

标签 python python-3.x tkinter combobox themes

我正在使用 TKinter(Python 3)开发 GUI。当我完成它后,我想为所有小部件设置一种颜色。我在更改文本和按钮小部件的颜色时没有任何问题,我只是使用了 bg 选项:

t = Text(master, wrap = WORD, bg = '#ffffb3')

然后,我尝试设置 ttk.Combobox 小部件的颜色,我注意到它们没有此选项,所以我最终使用主题更改了它们的颜色,如这篇文章中所述:How to set the background color of a ttk.Combobox 。但我在将主题应用到所有窗口时遇到了问题。如果您尝试以下代码,您将看到,主题仅适用于第一个窗口中的组合框,而不适用于按下按钮时创建的窗口中的组合框:

from tkinter import *
from tkinter import ttk

r = Tk()

def callback():
    r2 = Tk()

    c2 = ttk.Combobox(r2)
    c2.pack()

b = Button(r, text = 'Open', command = callback)
b.pack()

combostyle = ttk.Style()
combostyle.theme_create('combostyle', parent = 'alt', settings = {'TCombobox':{'configure':
    {'fieldbackground': '#ffff99', 'background': '#ffcc66'}}})
combostyle.theme_use('combostyle')

c = ttk.Combobox(r)
c.pack()

r.mainloop()

这是我第一次在 TKinter 中使用主题,所以如果我犯了一个愚蠢的错误,请原谅我。我通过互联网搜索并没有找到任何解决方案。任何帮助将不胜感激!

最佳答案

在一个程序中拥有多个 Tk 实例是一大禁忌。阅读 this answer 。在此引用:

Every tkinter program needs exactly one instance of Tk. Tkinter is a wrapper around an embedded tcl interpreter. Each instance of Tk gets its own copy of the interpreter, so two Tk instances have two different namespaces.

If you need multiple windows, create one instance of Tk and then additional windows should be instances of Toplevel.

因此,如果您需要多个窗口,请使用Toplevel。这是一个例子。

附注要设置 ttk 小部件的样式,请阅读 docs 。使用ttk.Style().configure()可以轻松完成。

import tkinter as tk
import tkinter.ttk as ttk

r = tk.Tk()

def callback():
    r2 = tk.Toplevel()

    c2 = ttk.Combobox(r2, style='ARD.TCombobox')
    c2.pack()

b = tk.Button(r, text = 'Open', command = callback)
b.pack()

combostyle = ttk.Style()
combostyle.configure('ARD.TCombobox', background="#ffcc66", fieldbackground="#ffff99")

c = ttk.Combobox(style='ARD.TCombobox')
c.pack()

r.mainloop()

关于python - 如何在所有窗口中设置组合框的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54160385/

相关文章:

python - 为什么设置窗口图标时没有定义 .ico 文件?

python - 如何将 `cv2.imwrite()` 输出到标准输出?

python - 组合和制表几个文本 block

python - 单文件 Django、DRF 项目

python - 如何创建 4 个标题,使其成为 CSV 文件中 pandas 数据框中 16 列的标题行?

Python 以可变间距拆分列

python - 如何将参数传递给 Tkinter 中的 Button 命令?

python - 动态类型设计 : is recursivity for dealing with lists a good design?

python - 名称错误 : name 'GATE_OP' is not defined #tensorflow

python - 如何使用 tkinter 创建菜单栏?