【问题标题】:ttk label doesn't behave properlyttk 标签行为不正常
【发布时间】:2016-09-13 11:08:12
【问题描述】:

当我更改图像的前景色时,包含位图图像的 ttk 标签无法正常运行。只有 ttk 标签有这个问题。 Tkinter 标签工作正常。

代码如下:

import tkinter as tk
import tkinter.ttk as ttk

BITMAP0 = """
#define zero_width 24
#define zero_height 32
static char zero_bits[] = {
0x00,0x00,0x00, 0x00,0x00,0x00, 0xf0,0x3c,0x0f, 0xf0,0x3c,0x0f,
0xf0,0x3c,0x0f, 0xf0,0x3c,0x0f, 0x00,0x00,0x00, 0x00,0x00,0x00,
0xf0,0x00,0x0f, 0xf0,0x00,0x0f, 0xf0,0x00,0x0f, 0xf0,0x00,0x0f,
0x00,0x00,0x00, 0x00,0x00,0x00, 0xf0,0x00,0x0f, 0xf0,0x00,0x0f,
0xf0,0x00,0x0f, 0xf0,0x00,0x0f, 0x00,0x00,0x00, 0x00,0x00,0x00,
0xf0,0x00,0x0f, 0xf0,0x00,0x0f, 0xf0,0x00,0x0f, 0xf0,0x00,0x0f,
0x00,0x00,0x00, 0x00,0x00,0x00, 0xf0,0x3c,0x0f, 0xf0,0x3c,0x0f,
0xf0,0x3c,0x0f, 0xf0,0x3c,0x0f, 0x00,0x00,0x00, 0x00,0x00,0x00
};
"""

root = tk.Tk()

img = tk.BitmapImage(data=BITMAP0, foreground='Lime', background='Black')

label = ttk.Label(root, image=img)
label.pack()

color = ['red', 'yellow', 'lime', 'white']

def change_color(n):
    img.config(foreground=color[n])
    if n == 3:
        root.after(1000, change_color, 0)
    else:
        root.after(1000, change_color, n+1)

root.after(1000, change_color, 0)

root.mainloop()

图像的前景色应该每秒改变一次,它不会改变,除非你用鼠标飞过图像。 只需替换该行:

label = ttk.Label(root, image=img)

与:

label = tk.Label(root, image=img)

并且该程序有效。 任何帮助将不胜感激。

我在 windows Vista 上使用 python 3.5

【问题讨论】:

  • 如果可以的话,为什么不直接使用 tk 标签呢?尝试使用 ttk 标签有什么好处?
  • 我程序的整个 GUI 都在使用 ttk。将 tkinter 用于单个小部件并不好。无论如何我认为这是一个 ttk 标签的错误。
  • ttk 的标签似乎需要一个元组作为图像的参数。尝试将其调用为label = ttk.Label(root, image=(img,))(注意() 中的逗号 - 这很重要,因此 Python 知道它应该是一个元组)
  • 不幸的是,元组 (img,) 没有改变,无论如何谢谢。奇怪的是,如果你用鼠标飞过图像,你会看到颜色发生变化。
  • 这是 ttk 实现的一个错误。请参阅core.tcl.tk/tk/tktview?name=3126428,其中还有一个建议的补丁来解决这个问题。与此同时,非 ttk 小部件将按预期更新,或者按照@acw1668 的建议强制重绘小部件将解决该问题。

标签: python python-3.x tkinter ttk


【解决方案1】:

尝试将更改后的图像重新分配给标签:

def change_color(n):
    img.config(foreground=color[n%4])
    label.config(image=img) # reassign the changed image to label
    root.after(1000, change_color, n+1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-18
    • 1970-01-01
    相关资源
    最近更新 更多