我在Tkinter中创建了一个导入图像的函数。但函数似乎正在执行,但我无法访问图像对象。为什么会出现这个问题
import tkinter
from PIL import ImageTk, Image
from tkinter import *
from tkinter import ttk
root = tkinter.Tk()
root.title("Guess Geek")
root.geometry("1280x720")
root.resizable(0, 0)
def importimg(x,y):
x=ImageTk.PhotoImage(file=y)
importimg('bgimg','main1.jpg')
bg = Label(root, image=bgimg, )
bg.place()
root.mainloop()
欢迎来到StackOverflow!我知道您已经接受了答案,但我想向您展示我对代码的看法:
以下是我在您的代码中所做的更改:
tkinter
和tkinter.ttk
的所有元素都放在全局范围内,而是只导入了模块tkinter
改名为tk
,把tkinter.ttk
改名为ttk
,以便于使用较短的名称PIL.ImageTk
模块,但没有将它们引入全局范围,只是为了确定它的来源PIL.Image
模块,但没有将它们放在全局范围内,因为如果将这两个模块都放在全局范围内,则有一个tkinter.Image
会覆盖它(您编写代码的方式)importimg()
返回从类PIL.ImageTk.PhotoImage()
创建的对象。这将被分配给bg_img
place()
几何体管理器,而是使用了grid()
的几何体管理器。它通常由TkDocs网站提供如果你有任何问题,尽管问
代码背后的思想是完美的。
bgimg
,这是因为在第15行中,您将bgimg
定义为字符串而不是变量而不是
试一试
.open()
方法来定义图像位置。使用此选项,还可以指定图像的Width
和Height
.open()
方法如果您仍然无法找出问题所在,请参考以下内容
相关问题 更多 >
编程相关推荐