无法使Ttk样式映射起作用

时间:2017-07-14 20:50:09

标签: python tkinter ttk

所以我环顾四周,但是关于风格的问题很少,但没有问题可以回答。

我无法让样式映射起作用。我不知道自己错过了什么。 如果你能纠正我,那将是伟大的,谢谢。

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()

1 个答案:

答案 0 :(得分:1)

框架样式不响应单击事件和鼠标悬停(悬停)事件。按钮呢。请参阅下面的代码并尝试一下。我也这样做,以便文本小部件以您尝试使帧响应的方式响应事件。由于文本窗口小部件不是主题窗口小部件,因此无法使用样式进行配置,但您可以使用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()