【问题标题】:Custom Tkinter Images自定义 Tkinter 图像
【发布时间】:2022-01-06 22:13:14
【问题描述】:

我正在尝试创建一个后退按钮。我在文件夹img 中有一个名为back-button.png 的图像。

这是我的代码:

from tkinter import *
import customtkinter as ctk

root = Tk()

ctk.CTkLabel(root, 
  text = 'This is a label', 
  text_font =('Verdana', 17)).pack(side = LEFT, pady = 11)

img = PhotoImage(file="./img/back-button.png")
ctk.CTkButton(root, image = img).pack(side = LEFT)

root.mainloop()

当我运行这段代码时,我得到了这个错误:

Traceback (most recent call last):
  File "c:\Users\User\Desktop\youtube-audio-downloader\tempCodeRunnerFile.py", line 11, in <module>
    ctk.CTkButton(root, image = img).pack(side = LEFT)
  File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\customtkinter\customtkinter_button.py", line 102, in __init__
    self.draw()
  File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\customtkinter\customtkinter_button.py", line 147, in draw
    self.canvas.configure(bg=CTkColorManager.single_color(self.bg_color, self.appearance_mode))
  File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1646, in configure
    return self._configure('configure', cnf, kw)
  File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1636, in _configure
    self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: unknown color name "."

那么,为什么会这样呢?以及如何在按钮上显示图像?

【问题讨论】:

  • 您的代码不可重现。错误消息与第 147 行有关,其内容在您问题的代码中根本不存在。发生这种情况是因为从 CTkColorManager.single_color() 返回的某些值(不在您的代码中;self.bg_colorself.appearance_mode 也不是)不是有效颜色。网站上有很多用于向按钮添加图像的代码;尝试四处搜索。

标签: python tkinter


【解决方案1】:

问题在于 CtkButton 小部件不像标准小部件那样接受参数。 CtkButton 的第一个参数是背景颜色,但您传递的是根窗口,而根窗口不是有效颜色。

您需要将根窗口显式分配给master 参数。

ctk.CTkButton(master=root, image = img).pack(side = LEFT)
#             ^^^^^^^

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-25
    • 1970-01-01
    • 1970-01-01
    • 2012-08-07
    • 2020-12-18
    • 1970-01-01
    • 1970-01-01
    • 2011-11-19
    相关资源
    最近更新 更多