python - 如何在 tkinter 中没有文本的按钮上添加图像?
问题描述
最近我在 tkinter 中制作了一个计算器,在其中我在计算器的左角创建了一个类似菜单的东西。在菜单中,我创建了 2 个按钮,分别命名为“Light Mode”和“Dark Mode”。我想在按钮“暗模式”上添加图像,而不是文本“暗模式”。但是当我用图像替换文本时,按钮不会在按钮上显示图像,而是显示名为“pyimage3”的东西
这就是创建和分配图像的内容,如下所示:
self.darkmode_img= PhotoImage(file="c:/Users/sheran/Downloads/Dark_Mode.png")
我希望这个 darkmode_img 出现在按钮上而不是文本上。
这是完整的代码:
f1=Frame(self.window,width=170,height=100,bg='#fff',borderwidth=0,bd=0)
f1.place(x=0,y=0)
# Buttons
def bttn(x,y,text,cmd):
def on_entera(event):
myButton1['background'] = '#F0F0F0' #ffcc66
myButton1['foreground']= '#262626' #000d33
def on_leavea(event):
myButton1['background'] = "#fff"
myButton1['foreground']= '#000'
myButton1 = Button(f1,text=self.darkmode_img,
width=42,
height=2,
fg='#000',
border=0,
bg="#fff",
borderwidth=0,
activeforeground='#262626',
activebackground="#F0F0F0",
command=cmd)
myButton1.bind("<Enter>", on_entera)
myButton1.bind("<Leave>", on_leavea)
myButton1.place(x=-65,y=32)
bttn(x=0,y=4,text=self.darkmode_img,cmd=self.darkmode_on)
def bttn2(x,y,text,cmd):
def on_entera(event):
myButton1['background'] = '#F0F0F0' #ffcc66
myButton1['foreground']= '#262626' #000d33
def on_leavea(event):
myButton1['background'] = "#fff"
myButton1['foreground']= '#000'
myButton1 = Button(f1,text=text,
width=42,
height=2,
fg='#000',
border=0,
bg="#fff",
activeforeground='#262626',
activebackground="#F0F0F0",
command=cmd)
myButton1.bind("<Enter>", on_entera)
myButton1.bind("<Leave>", on_leavea)
myButton1.place(x=-63,y=64)
bttn2(x=0,y=4,text="Light Mode",cmd=self.lightmode_on)
#
def dele():
f1.destroy()
global img2
img2 = ImageTk.PhotoImage(Image.open("c:/Users/sheran/Downloads/toggle_win/close1111.png"))
MB=Button(f1,
image=img2,
border=0,
command=dele,
bg='#fff',
activebackground='#fff').place(x=5,y=1)
def img1(self):
img1 = ImageTk.PhotoImage(Image.open("c:/Users/sheran/Downloads/toggle_win/open1111.png"))
def Button(self):
Button(self.window,image=self.img1,
command=self.toggle_win,
bd=0,
borderwidth=0,
bg='#f0f0f0',
activebackground='#fff').place(x=5,y=1)
在上面的那个结果中,它有“pyimage3”的地方,我需要把图像(self.darkmode_img)放在那个按钮上。
请帮我!!!我绝对是新手:)
解决方案
要将图像添加到按钮,您需要编写以下代码(这是一个示例):
from tkinter import *
root = Tk()
img = PhotoImage(file='image.png')
mybtn = Button(root, image=img, bd=0, cursor='hand2)
mybtn.image = img
mybtn.pack()
root.mainloop()
大多数情况下,当您没有放置第 3 行或第 1 行中没有放置文件选项时,就会发生错误。
推荐阅读
- php - 如何使用 Ghostscript 将 TTF 格式的字体嵌入 PDF?
- go - go.mod 未解决的依赖
- php - 如何在多维 JSON 字符串中包含变量?
- python - 停止任务 discord.py
- python - 根据日期和 ID 从数据框中选择最大值
- jenkins - 使用 jenkins 中的单个管道将应用程序套件部署到 8 个环境
- c++ - 从 DLL 访问结构的成员,在 C++ 中运行时加载
- c# - 自动 DataGridView 单个单元格的前景
- ruby-on-rails - Ruby on Rails 错误 - Alchemy:Module 的 NoMethodError 未定义方法“gem_version”
- kubernetes - 使用 helm 更新 Kubernetes 作业