首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何动态更改ttk按钮字体颜色和背景

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

Stack Overflow用户
提问于 2020-03-15 21:04:49
回答 1查看 299关注 0票数 1

我试过各种方法来做这件事,但我错过了一些东西。在乞讨中,我认为我需要创建一种样式,而不是将其分配给按钮。

代码语言:javascript
运行
复制
st = ttk.Style()
st.configure('blueTButton', foreground="white", background="blue")
Btn.configure(style='blueTButton')

但是我得到了一个错误:_tkinter.TclError:布局blueTButton未找到

所以我试了一下:

代码语言:javascript
运行
复制
Btn.configure(foreground = 'red')
# and also
Btn.config(foreground = 'red')

还有其他许多愚蠢的尝试。

有人能帮忙吗?

EN

回答 1

Stack Overflow用户

发布于 2022-09-05 19:44:39

由于您使用的是ttk包,所以必须使用Style对该包中使用的小部件进行任何修改。

要动态地更改它们,例如按下按钮,将对小部件的引用传递给函数,以执行您喜欢的任何操作。我个人决定也传递一个对Style对象的引用,这样就不需要用每个函数调用重新创建它了。修改此示例代码以满足您的需要。

代码语言:javascript
运行
复制
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()

按每一个按钮改变帧的颜色:

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60697631

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档