繁体   English   中英

如何动态更改 ttk 按钮字体颜色和背景

[英]how do I dynamically change ttk button font color and background

我尝试了各种方法来做到这一点,但我错过了一些东西。 在开始时,我认为我需要创建一种样式并将其分配给按钮

st = ttk.Style()
st.configure('blueTButton', foreground="white", background="blue")
Btn.configure(style='blueTButton')

但我收到一个错误:_tkinter.TclError: Layout blueTButton not found

所以我尝试了这个:

Btn.configure(foreground = 'red')
# and also
Btn.config(foreground = 'red')

以及许多其他愚蠢的尝试。

有人可以帮忙吗?

由于您使用的是ttk package,因此您必须使用Style将任何修改应用于从该 package 使用的小部件。

要动态更改它们,例如按下按钮,请将小部件的引用传递给 function 以执行您喜欢的任何操作。 我个人还决定传递对Style object 的引用,因此不需要在每个 function 调用中重新创建它。 修改此示例代码以满足您的需要。

import tkinter as tk
# Using cycle for demonstration purposes
from itertools import cycle
from tkinter import ttk

class TKTEST:

    def __init__(self) -> None:
        self.tkapp()

    def tkapp(self) -> None:

        root = tk.Tk()
        root.title("Test Dynamic Color Change")
        root.geometry("300x300")

        # Create style object before button
        style = ttk.Style()

        # Create a collection of colors to cycle through
        colors = cycle(["#e9c46a","#e76f51","#264653","#2a9d8f","#e85d04","#a2d2ff","#06d6a0","#4d908e"])

        # Using pack() to stretch out the frame to the size of the window
        mainframe = ttk.Frame(master=root, relief="groove")
        mainframe.pack(fill="both", expand=True)

        # Use place() to center the button horizontally and vertically in the frame
        # Use a lambda function to be able to pass arguments to the called function
        button = ttk.Button(master=mainframe, text="Change Colors", command=lambda: self.change_frame_color(mainframe, style, colors))
        button.place(relx=0.5, rely=0.5, anchor="center")

        root.mainloop()

    # Using type hinting with method arguments
    def change_frame_color(self, objFrame: ttk.Frame, style: ttk.Style, colors: cycle) -> None:
        # First, apply a style to frame since we're using ttk package
        objFrame.configure(style="Mainframe.TFrame")
        # Second, configure the style with a background color
        style.configure("Mainframe.TFrame", background=next(colors))


tktest = TKTEST()

每次按下按钮都会更改框架的颜色:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM