我试过各种方法来做这件事,但我错过了一些东西。在乞讨中,我认为我需要创建一种样式,而不是将其分配给按钮。
st = ttk.Style()
st.configure('blueTButton', foreground="white", background="blue")
Btn.configure(style='blueTButton')
但是我得到了一个错误:_tkinter.TclError:布局blueTButton未找到
所以我试了一下:
Btn.configure(foreground = 'red')
# and also
Btn.config(foreground = 'red')
还有其他许多愚蠢的尝试。
有人能帮忙吗?
发布于 2022-09-05 19:44:39
由于您使用的是ttk
包,所以必须使用Style
对该包中使用的小部件进行任何修改。
要动态地更改它们,例如按下按钮,将对小部件的引用传递给函数,以执行您喜欢的任何操作。我个人决定也传递一个对Style
对象的引用,这样就不需要用每个函数调用重新创建它了。修改此示例代码以满足您的需要。
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()
按每一个按钮改变帧的颜色:
https://stackoverflow.com/questions/60697631
复制相似问题