使用Tkinter的GUI - 不显示PNG背景图像?

时间:2016-12-12 21:51:27

标签: python user-interface tkinter

我目前正在尝试将一个.png图像显示在我创建的GUI的背景中,以向用户提问。但是,我的背景不会显示。我已经查看了类似的问题,建议将图像分配给label.image,这样就不会在垃圾收集中删除它。但是,即使我这样做也不会显示。图像的print语句返回“pyimage1”,所以我知道程序接受它是什么,但无济于事。任何帮助将不胜感激!

import tkinter
import os

#Defining main window to work in
root = tkinter.Tk()
root.geometry("1000x500")
root.title("GUI testing program")

questionText = "Question placeholder"
responseText = "Response text placeholder"

#Defining the image to use (got the exact filepath by using os.getcwd() )
imgfile         = tkinter.PhotoImage( file = (os.getcwd() + '\\test_img.gif') )
#Debugging print, which returns 'pyimage1'
print(imgfile)
#Assigning the image to the background label which will hold the image
backgroundimg   = tkinter.Label(root, image = imgfile)
backgroundimg.image = imgfile
backgroundimg.place(x = 0, y = 0, relx = 1.0, rely = 1.0, anchor = 'nw')

#Other items on the screen at the time
questionLabel   = tkinter.Label(root, text = questionText, font = ('Verdana',30), bg = '#ffffff', fg = '#000000', relief = 'sunken', justify = 'left', anchor = 'w')
questionLabel.pack(fill = 'x', side = 'top')
inputText       = tkinter.Entry(root, text = "Type answer here", font = ('Verdana',30), bg = '#ffffff', fg = '#000000')
inputText.pack(fill = 'x', side = 'top')
submitButton    = tkinter.Button(root, text = "Submit", font = ('Verdana',20), bg = '#2c3e50', fg = '#000000', activebackground = '#b3b3b3')
submitButton.pack(side = 'right', anchor = 'n')
responseLabel   = tkinter.Label(root, text = responseText, font = ('Verdana',20), bg = '#0000ff', fg = '#ffffff')
responseLabel.pack(side = 'left', anchor = 'n')

root.mainloop()

1 个答案:

答案 0 :(得分:0)

您将图像的左上角(anchor='nw')放在GUI的右下角(relx=1.0, rely=1.0)。整个图像都在屏幕外。

这是relx的文档;除了方向之外,rely是相同的:

  

位置指定主窗口中的x坐标   窗口的锚点。在这种情况下,位置在a中指定   相对时尚作为浮点数:0.0对应于   主机的左边缘和1.0对应的右边缘   主。位置不必在0.0-1.0的范围内。如果-x和   为从属指定-relx,然后将它们的值相加。例如,-relx 0.5 -x -2将从属的左边缘定位为2个像素   在其主人的中心左侧。

相关问题