如何在 tkinter 中制作具有左右功能的图像查看器? [英] How to make a image viewer with left right functionality in tkinter?
问题描述
我在 list
中有一堆链接和标签,可以查看我想要制作具有 next、previous 功能的图像查看器的链接和标签.我的各个图像的链接和标签在 list
中.到目前为止,我已经尝试过这个:
I have bunch of links and labels in list
to view those I want to make a image viewer with next, previous functionality. My links and labels for respective images are in list
. Up to now I had tried this :
urls=[url,url1,url2,url3]
labels=["label 1","label 2","label 3","label 4"]
images=[]
for ur in urls:
raw_data = urllib.request.urlopen(ur).read()
im = Image.open(io.BytesIO(raw_data))
image = ImageTk.PhotoImage(im)
images.append(image)
现在我在 images
中准备好了图像,现在我想在图像查看器中显示它,但在图像查看器中只能看到最后一张图像.
Now I have images ready in images
and now I want to display it in image viewer but only last image is visible in image viewer.
Label(root).grid(row=1,column=1)
for i in range(len(images)):
image_label=Label(root,image=images[i])
image_label.grid(row=1,column=2)
name=Label(root,text=labels[i])
name.grid(row=2,column=2)
def left():
image_label=Label(root,image=images[i-1])
image_label.grid(row=1,column=2)
def right():
image_label=Label(root,image=images[i+1])
image_label.grid(row=1,column=2)
left_button=Button(root,text="Left",command=left)
left_button.grid(row=2,column=1)
right_button=Button(root,text="Right",command=right)
right_button.grid(row=2,column=3)
右按钮不起作用,左按钮起作用,但只有一次.当我第二次单击左按钮时,什么都不起作用.
单击右键时出错:
Right button is not working and left button is working but for one time only. When I click left button second time then nothing is working.
Error while clicking in right button :
line 45, in right
image_label=Label(root,image=images[i+1])
IndexError: list index out of range
推荐答案
应该只在左移或右移时更新图像标签,而不是创建新标签.使用模数 %
找出下一回合.
Should just update a image label when shift left or right, not create a new label.
Using modulus %
to find which one next turn.
为了减少代码和可执行文件,我使用了 PySimpleGUI 中的图像数据和简单的图像名称.
To reduce code and executable, I use the image data in PySimpleGUI and simple name for image here.
import tkinter as tk
import PySimpleGUI as sg
def shift(num):
global index
index = (index + num) % size
label1.configure(image=images[index])
label2.configure(text =labels[index])
root = tk.Tk()
images = [tk.PhotoImage(data=image) for image in sg.EMOJI_BASE64_HAPPY_LIST]
size = len(images)
labels = [f'Image {i:0>2d}' for i in range(size)]
index = 0
label1 = tk.Label(root, image=images[index])
label1.grid(row=1, column=2)
label2 = tk.Label(root, text=labels[index])
label2.grid(row=2, column=2)
button1 = tk.Button(root, text="<LEFT", width=6, anchor='center', command=lambda num=-1:shift(num))
button1.grid(row=1, column=1)
button2 = tk.Button(root, text="RIGHT>", width=6, anchor='center', command=lambda num=+1:shift(num))
button2.grid(row=1, column=3)
root.mainloop()
这篇关于如何在 tkinter 中制作具有左右功能的图像查看器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!