【发布时间】:2021-11-23 05:19:34
【问题描述】:
最近我在 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)
here is what I'm getting as the result:
在上面的结果中,它有“pyimage3”的地方,我需要将图像(self.darkmode_img)放在那个按钮上。
请帮帮我!!!我绝对是个新手 :)
【问题讨论】:
-
尝试将
myButton1 = Button(f1,text=self.darkmode_img,更改为myButton1 = Button(f1, image=self.darkmode_img,。 -
@Derek 我这样做了......结果是只有空白的白色没有图像,也没有按钮本身......结果是:[这里是结果]( im5.ezgif.com/tmp/ezgif-5-8bdab9b4dce7.gif)
-
@SheranFernando:无论如何,您不能将图像传递给
text参数并期望它将图像添加到按钮。text仅用于文本。它显示"pyimage2"的原因是因为这是尝试将PhotoImage转换为字符串时返回的内容。 -
@SylvesterKruin 好的....那么我如何将图像放在按钮上
-
@SheranFernando:正如Derek 建议的那样:
image=self.darkmode_img。这是将图像添加到Button的唯一方法。
标签: python image tkinter button