所以我环顾四周,但是关于样式的问题很少,但是没有一个回答。
我无法使样式映射正常工作。我不知道我在想什么。
如果您能纠正我,那就太好了,谢谢。
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
s = ttk.Style()
s.map("C.TFrame",
foreground=[("pressed", "red"), ("active", "blue")],
background=[("pressed", "!disabled", "black"), ("active", "white")])
frame = ttk.Frame(root, style="C.TFrame")
text = ttk.Label(frame, text="This is some really long text\n123...")
frame.grid()
text.grid()
root.mainloop()
最佳答案
框架样式不响应单击事件和鼠标悬停(悬停)事件。按钮呢。请参阅下面的代码,然后尝试一下。我还做到了这一点,以便文本小部件以您试图使框架响应的方式响应事件。由于文本窗口小部件不是主题窗口小部件,因此无法使用样式进行配置,但是可以使用tk options
与此类似地配置应用程序,并将其保存在单独的文件中。但这是一个不同的故事。
def configureTextWindow(**kwargs):
for avp in kwargs.items():
attrib, value = avp
text[attrib] = value
s = ttk.Style()
# This won't work because frames don't respond to style events.
s.map("C.TFrame",
foreground=[("pressed", "red"), ("active", "blue")],
background=[("pressed", "!disabled", "black"), ("active", "white")])
# Does work because buttons DO respond to style events.
s.map("C.TButton",
foreground=[("pressed", "red"), ("active", "blue")],
background=[("pressed", "!disabled", "black"), ("active", "white")])
frame = ttk.Frame(root, style="C.TFrame")
button = ttk.Button(frame, style='C.TButton', text='Press or Hover')
button.grid()
text = ttk.Label(frame, text="This is some really long text\n123...")
frame.grid()
text.grid()
# Force configuration on the text widget that mimics the frame style above.
text.bind('<Enter>', lambda event: configureTextWindow(foreground='blue', background='white'))
text.bind('<Leave>', lambda event: configureTextWindow(foreground='black', background=''))
text.bind('<Button-1>', lambda event: configureTextWindow(foreground='red', background='black'))
text.bind('<ButtonRelease-1>', lambda event: configureTextWindow(foreground='blue', background='white'))
root.mainloop()