函数在Tkinter中添加图像

2024-09-29 17:11:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我在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()

Tags: 对象函数from图像imageimportpiltkinter
2条回答

欢迎来到StackOverflow!我知道您已经接受了答案,但我想向您展示我对代码的看法:

import tkinter as tk
import tkinter.ttk as ttk
import PIL.ImageTk
import PIL.Image

root = tk.Tk()
root.title("Guess Geek")
root.geometry("1280x720")
root.resizable(0, 0)

def importimg(file_name):
    return PIL.ImageTk.PhotoImage(PIL.Image.open(file_name))

bg_img = importimg('main1.jpg')
bg = ttk.Label(root, image=bg_img)
bg.grid(column=0, row=0)
root.mainloop()

以下是我在您的代码中所做的更改:

  • 我没有将tkintertkinter.ttk的所有元素都放在全局范围内,而是只导入了模块
  • 我把tkinter改名为tk,把tkinter.ttk改名为ttk,以便于使用较短的名称
  • 我导入了PIL.ImageTk模块,但没有将它们引入全局范围,只是为了确定它的来源
  • 我导入了PIL.Image模块,但没有将它们放在全局范围内,因为如果将这两个模块都放在全局范围内,则有一个tkinter.Image会覆盖它(您编写代码的方式)
  • ^{}第一个参数应该是PIL的映像(由^{}轻松提供),而不是文件名
  • importimg()返回从类PIL.ImageTk.PhotoImage()创建的对象。这将被分配给bg_img
  • 我没有使用place()几何体管理器,而是使用了grid()的几何体管理器。它通常由TkDocs网站提供

如果你有任何问题,尽管问

代码背后的思想是完美的。

  1. 这里的问题是代码无法将映像分配给变量bgimg,这是因为在第15行中,您将bgimg定义为字符串而不是变量

而不是

importimg('bgimg','main1.jpg')

试一试

bgmain = 0
importimg(bgimg,'')
  1. 程序可能找不到映像的目录。我建议您使用.open()方法来定义图像位置。使用此选项,还可以指定图像的WidthHeight

.open()方法

path = ".\imagename.jpg" or ".\images\imgname.jpg" or "F:\New folder\imgname.jpg"
k = Image.open(path)
k = k.resize((300,300), Image.ANTIALIAS)
bgimg = ImageTk.PhotoImage(k)

LABEL = Label(bg="black", image=bgimg)
LABEL.place(height=300, width=300)

如果您仍然无法找出问题所在,请参考以下内容

from tkinter import *
from PIL import ImageTk, Image

root = Tk()
root.title("Guess Geek")
root.geometry("1280x720")
root.resizable(0, 0)

def importimg(x,y):
    path = y
    k = Image.open(path)
    k = k.resize((400,400),Image.ANTIALIAS)
    x=ImageTk.PhotoImage(k)
    global bgimg
    bgimg = x

bgimg = 0
importimg(bgimg,".\foldername\imagename.jpg")
bg = Label(root, image=bgimg )
bg.place(width=400, height=400, relx=0.05, rely=0.1)
root.mainloop()

相关问题 更多 >

    热门问题