无法在 tkinter 的 canvas 中显示多于一张图像
Cannot Display More than one images in the canvas of tkinter
我正在尝试通过 one.But 创建系列一中的图像渲染,通常它显示最后一张图像和其他图像 invisible.I 发现参考变量有问题(cj.img = t) 我应该在每个 time.What 保持不变???
import tkinter
from tkinter import *
import PIL
from PIL import Image,ImageTk
#--------------------------------------------------------------------------------------------------
root = Tk()
root.geometry("600x400")
cj = Canvas(root,width = 600,height = 300,relief = SUNKEN,bd = 1,bg = "#494949")
cj.grid(row = 1,column = 0,sticky = "news")
w = 0
imh = ["myphoto.png","new2.png","format.png"]
def showimg():
for i in range(len(imh)) :
t = ImageTk.PhotoImage(file = imh[i])
cj.img = t
cj.create_image(100,(i * 50),image = t,anchor = N)
showimg()
快到了。每张图片必须单独定义,否则图片t
会覆盖上一张。所以下面的代码应该给出提示。
from tkinter import Tk, Canvas, SUNKEN
import PIL
from PIL import Image, ImageTk
root = Tk()
root.geometry('600x400')
cj = Canvas(root, width=600, height=300, relief=SUNKEN, bd=1, bg="#494949")
cj.grid(row=1, column=0, sticky='nesw')
image_files = ['myphoto.png', 'new2.png', 'format.png']
pics = []
def show_img():
for i, image_file in enumerate(image_files):
pics.append(ImageTk.PhotoImage(file=image_file))
cj.create_image(100, i * 50, image=pics[i], anchor='n')
show_img()
root.mainloop()
提示:
- 不导入 *
- 在 for 循环中使用 enumerate() 获取索引 i 和 file_name
- 使用更具描述性的文件名
- 根据 PEP8,在逗号
后添加 space
一些有用的文档:The Tkinter Canvas Widget
我正在尝试通过 one.But 创建系列一中的图像渲染,通常它显示最后一张图像和其他图像 invisible.I 发现参考变量有问题(cj.img = t) 我应该在每个 time.What 保持不变???
import tkinter
from tkinter import *
import PIL
from PIL import Image,ImageTk
#--------------------------------------------------------------------------------------------------
root = Tk()
root.geometry("600x400")
cj = Canvas(root,width = 600,height = 300,relief = SUNKEN,bd = 1,bg = "#494949")
cj.grid(row = 1,column = 0,sticky = "news")
w = 0
imh = ["myphoto.png","new2.png","format.png"]
def showimg():
for i in range(len(imh)) :
t = ImageTk.PhotoImage(file = imh[i])
cj.img = t
cj.create_image(100,(i * 50),image = t,anchor = N)
showimg()
快到了。每张图片必须单独定义,否则图片t
会覆盖上一张。所以下面的代码应该给出提示。
from tkinter import Tk, Canvas, SUNKEN
import PIL
from PIL import Image, ImageTk
root = Tk()
root.geometry('600x400')
cj = Canvas(root, width=600, height=300, relief=SUNKEN, bd=1, bg="#494949")
cj.grid(row=1, column=0, sticky='nesw')
image_files = ['myphoto.png', 'new2.png', 'format.png']
pics = []
def show_img():
for i, image_file in enumerate(image_files):
pics.append(ImageTk.PhotoImage(file=image_file))
cj.create_image(100, i * 50, image=pics[i], anchor='n')
show_img()
root.mainloop()
提示:
- 不导入 *
- 在 for 循环中使用 enumerate() 获取索引 i 和 file_name
- 使用更具描述性的文件名
- 根据 PEP8,在逗号 后添加 space
一些有用的文档:The Tkinter Canvas Widget