我可以用图片作为Toplevel()中按钮上的图标吗?

2024-04-18 21:28:38 发布

您现在位置:Python中文网/ 问答频道 /正文

在python中,我可以使用图片作为Tk()实例中按钮上的图标。但是当我尝试在Toplevel()的情况下使用图片时,它不起作用。 代码:

from tkinter import *
root=Tk()
root.title("Login Window")
root.geometry("300x300")
def mainpage():
    mp=Toplevel()
    mp.title("Main Page")
    new_img=PhotoImage(file="nen.png")
    sea_img=PhotoImage(file="serch.png")
    al_img=PhotoImage(file="shw.png")
    Button(mp,image=new_img).pack(side="top",pady=0)
    Label(mp,text="New Entry",bd=0).pack(side="top",padx=0,pady=0)
    Button(mp,image=sea_img,bd=0,command=srch).pack(side="top")
    Label(mp,text="Serach Record",bd=0).pack(side="top",padx=0,pady=0)
    Button(mp,image=al_img,bd=0,command=al_rcrd).pack(side="top",pady=0)
    Label(mp,text="All Record",bd=0).pack(side="top",padx=0,pady=0)
Label(root,text="User-Id",font=15).grid(row=0,column=0,padx=10,pady=10,sticky=W)
Entry(root).grid(row=0,column=1)
Button(root,text="Login",font=15,command=mainpage).grid(row=1,column=1,padx=10,pady=10)

root.mainloop()  

Tags: textimgpngtopbuttonmprootside
1条回答
网友
1楼 · 发布于 2024-04-18 21:28:38

如果我知道您想在Toplevel窗口中的button上显示image。图像将在toplevel中收集,直到您引用B.image= new_img它,以便它将显示在窗口中。要在LabelToplevel上显示,还需要保存对它的引用

from tkinter import *


root=Tk()
root.title("Login Window")
root.geometry("300x300")


def mainpage():
    mp=Toplevel()
    mp.title("Main Page")
    new_img=PhotoImage(file="nen.png")
    B = Button(mp, image=new_img)
    B.image= new_img
    B.pack()

Label(root,text="User-Id",font=15).grid(row=0,column=0,padx=10,pady=10,sticky=W)

Entry(root).grid(row=0,column=1)

Button(root,text="Login",font=15,command=mainpage)
grid(row=1,column=1,padx=10,pady=10)

root.mainloop()

相关问题 更多 >