【问题标题】:GUI with Tkinter - PNG background image not displaying?带有 Tkinter 的 GUI - 不显示 PNG 背景图像?
【发布时间】:2017-04-27 20:57:48
【问题描述】:

我目前正在尝试获取 .png 图像以显示在我为向用户提问而创建的 GUI 的背景中。但是,我的背景不会显示。我已经查看了与此类似的问题,建议将图像分配给 label.image,这样它就不会在垃圾收集中被删除。但是,即使我这样做了,它也不会显示。图像的打印语句返回“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()

【问题讨论】:

    标签: python user-interface tkinter


    【解决方案1】:

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

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

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

    【讨论】:

    • 哦,谢谢,我认为它的长度与屏幕大小有关!
    • @D.Lee:可以使用relwidthrelheight 指定对象大小。
    猜你喜欢
    • 2012-10-16
    • 2014-06-03
    • 2017-08-20
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 2015-06-21
    • 1970-01-01
    • 2018-03-15
    相关资源
    最近更新 更多