Python 3.x tkinter无法显示图像

Python 3.x tkinter无法显示图像,python-3.x,tkinter,Python 3.x,Tkinter,我想在tkinter的按钮中放置一个图像(light.gif)。 但是,不会显示图像,并且在指定位置仅显示一个小的透明框 我的代码是 from tkinter import* #To use Tkinter from tkinter import ttk #To use Tkinter from tkinter import messagebox #To use Tkinter import tkinter.font # To use Font win = Tk() win.title("Ma

我想在tkinter的按钮中放置一个图像(light.gif)。 但是,不会显示图像,并且在指定位置仅显示一个小的透明框

我的代码是

from tkinter import* #To use Tkinter
from tkinter import ttk #To use Tkinter
from tkinter import messagebox #To use Tkinter
import tkinter.font # To use Font

win = Tk()
win.title("Main Control")
win.geometry('450x400+100+300')
win.resizable(0,0)

def a1():
     a1 = Toplevel()
     a1.title("a1")
     a1.geometry('450x350+560+100')
     a1.resizable(0,0)

     lignt_sensor_image=PhotoImage(file = 'light.gif')
     light_sensor_button=Button(a1,width=15,height=8)
     light_sensor_button.place=(x=275,y=200)
     a1.mainloop()

newa1 = Button(win, text='A1', font=font1, command=a1, height = 5, width = 10)
newa1.place(x=50, y=30)
win.mainloop()

请帮助我

您必须保留对该图像的引用;由于它是在函数中创建的,因此它在函数退出时被销毁。
您的代码中也有一些拼写错误,使其无法运行

下面显示了弹出窗口中的图像

import tkinter as tk
from tkinter import PhotoImage


def spawn_toplever_a1(): 
    global light_sensor_image                  # <- hold the image in the global variable, so it persists
    a1 = tk.Toplevel()                         # do not name your variables the same as your function
    a1.title("a1")
    a1.geometry('450x350+560+100')
    light_sensor_image = PhotoImage(file='light.gif')
    light_sensor_button = tk.Button(a1, image=light_sensor_image, text="my image", compound="center")

    light_sensor_button.place(x=275,y=100)   # <-- typo - removed '=' sign
                                             # <-- removed call to mainloop

light_sensor_image = None                    # declare variable to hold the image

win = tk.Tk()
win.title("Main Control")
win.geometry('450x400+100+300')
win.resizable(0,0)    

newa1 = tk.Button(win, text='A1', command=spawn_toplever_a1, height = 5, width = 10)
newa1.place(x=50, y=30)
win.mainloop()
将tkinter作为tk导入
从tkinter导入PhotoImage
def spawn_toplever_a1():

全球光传感器图像考虑到你告诉我的,它运行干净。非常感谢。