[英]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.