【问题标题】:Adding images to toplevel window将图像添加到顶层窗口
【发布时间】:2019-11-16 23:20:58
【问题描述】:

我正在尝试在 python 的顶级窗口中添加图像,但似乎无法正常工作。

我尝试过使用画布并在堆栈溢出方面遵循其他一些步骤。我没有尝试过的一件事是使用类、init 和 self,但我不太明白,希望不使用 self 也能实现我的目标。和类似的东西:D。

  def pika():
    def close():
        win.destroy()
    win = Toplevel()
    win.geometry("150x150")
    win.title("I CHOOSE U")
    yellowb = Label(win, bg = 'yellow', fg = 'yellow', padx = 100, pady = 100)
    yellowb.pack()
    poke = PhotoImage(file = "pika.gif")
    pika = Label(image = poke) # REEEEEEEEEEEEEEEEEE IT NO WORKEY
    pika.grid(row = 0, column=1, padx = 10, pady = 10)
    button = Button(win, text = "Close", command = close) 
    button.place(x=49, y=130)

这是主窗口代码

win = Tk()
win.geometry("290x200")
win.title('Error')
text1 = Label(win, bg= "Cyan", fg = 'Teal', padx = 50, pady = 75, text = '#hash error',
              font = ('Times', '40', 'bold'))
text1.place(x=win.winfo_width() / 2, y=win.winfo_width() / 2)
button1 = Button(win, text = 'green', command = green)
button1.place(x=40, y=160)
button2 = Button(win, text = 'blue', command = blue)
button2.place(x=90, y=160)
button3 = Button(win, text = "red", command = red)
button3.place(x=130, y=160)
button4 = Button(win, text = 'yellow', command = yellow)
button4.place(x=170, y=160)
button5 = Button(win, text = "orange", command = orange)
button5.place(x=229, y=160)
eggs = PhotoImage(file = "pika.gif")  
eggpic = Button(win, image = eggs, bg = 'Cyan', fg = 'Cyan', command = pika)
eggpic.place(x=100, y=20)
def close():
    win.destroy()
closebut = Button(win, text='close', command = close)
closebut.place(x=0, y=0)

当我点击一个按钮并打开一个新窗口时,窗口的背景是黄色的,一切都如预期的那样,但是图像没有出现在窗口上,并且图像大小的白框出现在主窗口中tk 窗口。

https://imgur.com/a/XU5m3Se

【问题讨论】:

  • 我对 tkinter 很陌生,所以我真的不知道如何使用 self.而且看起来很吓人。
  • 只能使用def close(): win.destroy()command=close 而不是command=win.destroy

标签: python tkinter


【解决方案1】:

你可能有两个问题:


首先:每个小部件都需要父级。如果您不使用它,那么 tkinter 将小部件分配给主窗口。

而你在Label(image = poke) 中遇到了这个问题,因为你忘记了win

 pika = Label(win, image=poke)

这就是您在主窗口中看到矩形而不是顶层窗口的原因。


第二个:PhotoImage有bug。 Garbage Collector 在函数中创建并分配给局部变量时将其从内存中删除。然后你可以看到空图像。

您必须将PhotoImage 分配给全局变量或分配给函数中的其他小部件。

分配给其他小部件的流行解决方案:

poke = PhotoImage(file = "pika.gif")
pika = Label(win, image=poke)
pika.photo = poke # <-- assign PhotoImage to other widget too

更多:PhotoImage

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-16
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    • 2018-09-09
    相关资源
    最近更新 更多