为什么函数不能在tkinter python标签上获得显示图像,但它不能使用函数
这段没有函数的代码用于获取标签tkinter python 3.8.5上的显示图像为什么函数不能在tkinter python标签上获得显示图像,但它不能使用函数,python,image,tkinter,Python,Image,Tkinter,这段没有函数的代码用于获取标签tkinter python 3.8.5上的显示图像 from tkinter import * from PIL import Image, ImageTk import os import os.path root = Tk() root.title("Test_image") root.geometry("1000x600") # def display
from tkinter import *
from PIL import Image, ImageTk
import os
import os.path
root = Tk()
root.title("Test_image")
root.geometry("1000x600")
# def display_image():
images_folder = "C:/TextSoundSource/B-V/I-WORD-E-00-B-V-0-renamed"
os.chdir(images_folder)
displaying_img = "022.jpg"
# Open Image
img = Image.open(displaying_img)
# Resize Image
resized = img.resize((300, 200), Image.ANTIALIAS)
resized_img = ImageTk.PhotoImage(resized)
image_display_frame = LabelFrame(root, text="Image", font=(
"times", 15, "bold"), bg="Navyblue", fg="white", bd=5)
image_display_frame.place(x=0, y=0, width=1000, height=300)
img_label = Label(image_display_frame, image=resized_img)
img_label.pack(pady=20)
# display_image()
root.mainloop()
但当使用下面这样的函数时,它不起作用,我如何使用该函数获取图像
from tkinter import *
from PIL import Image, ImageTk
import os
import os.path
# == == == == == == == == == == == ========
# Using function does not work ???? why ???
# == == == == == == == == == == == ========
root = Tk()
root.title("Test_image")
root.geometry("1000x600")
def display_image():
images_folder = "C:/TextSoundSource/B-V/I-WORD-E-00-B-V-0-renamed"
os.chdir(images_folder)
displaying_img = "001.jpg"
# Open Image
img = Image.open(displaying_img)
# Resize Image
resized = img.resize((300, 200), Image.ANTIALIAS)
resized_img = ImageTk.PhotoImage(resized)
image_display_frame = LabelFrame(root, text="Image", font=(
"times", 15, "bold"), bg="Navyblue", fg="white", bd=5)
image_display_frame.place(x=0, y=0, width=1000, height=300)
img_label = Label(image_display_frame, image=resized_img)
img_label.pack(pady=20)
display_image()
root.mainloop()
我提前表示感谢,请让我知道如何使用tkinter python中的函数来获得图像显示。在python中,函数对对象名称有自己的局部作用域。退出函数时,所有名称都会被垃圾收集,程序无法使用 如@Cool cloud所示,您可以使用
global
关键字将图像引用添加到全局范围。另一种常用技术是将图像引用保存到标签小部件:
img_label.image = resized_img
在Python中,函数有自己的对象名局部作用域。退出函数时,所有名称都会被垃圾收集,程序无法使用 如@Cool cloud所示,您可以使用
global
关键字将图像引用添加到全局范围。另一种常用技术是将图像引用保存到标签小部件:
img_label.image = resized_img
在函数中添加
global resized\u img
,或者只添加root.anything=resized\u img
。在函数中添加global resized\u img
,或者只添加root.anything=resized\u img
。这对我来说是一个非常有用的关键答案。对我来说,这是一个非常有用的关键答案。它起作用了。