python - 如何在 tkinter 中制作具有左右功能的图像查看器?
问题描述
我有一堆链接和标签list
来查看我想要制作具有下一个、上一个功能的图像查看器的那些。我的各个图像的链接和标签位于list
. 到目前为止,我已经尝试过:
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
,现在我想在图像查看器中显示它,但在图像查看器中只有最后一张图像可见。
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)
右键不工作,左键工作,但只有一次。当我第二次单击左键时,没有任何效果。
单击右键时出错:
line 45, in right
image_label=Label(root,image=images[i+1])
IndexError: list index out of range
解决方案
该代码非常接近原始发布的示例。
没有lambda
in Button
,只是直接command
可以访问左右功能。
名称标签是不必要的,因为label
对象已经具有text
属性,因此我将图像和文本集成为单个label
并增加了字体大小。
label
复合用于控制图像相对于文本的显示位置,我选择了top
. 也就是说,图像将放置在文本上方。
使用global
in 函数跟踪count
from tkinter import Tk, Label, Frame, Button
from PIL import ImageTk, Image
import io
import requests
import urllib
root = Tk()
urls = [url, url1, url2, url3]
labels = ["label 1","label 2","label 3","label 4"]
count = -1
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)
def left( ):
global count
count = (count - 1) % len(images)
image_label.config(image = images[count], text = labels[count])
def right( ):
global count
count = (count + 1) % len(images)
image_label.config(image = images[count], text = labels[count])
image_label = Label(
root, image = images[count], font = "Helvetica 20 normal",
text = labels[count], compound = "top")
image_label.grid(row = 0, column = 0, columnspan = 2, sticky = "nsew")
Button(
root, text = "<< LEFT", command = left).grid( row = 1, column = 0, sticky = "ew")
Button(
root, text = "RIGHT >>", command = right).grid(row = 1, column = 1, sticky = "ew")
right( ) # display first image
root.mainloop()
推荐阅读
- python - How can I find the optimal parameters for a function?
- reactjs - 如何在 ReactJS 的功能组件中编写 this.handle click
- c# - Function that outputs grid of controls
- javascript - 在 ajax 请求中获取特殊标签
- r - how to sum raster layer to raster stack R
- git - How to split changes in multiple linked working trees?
- csv - 如何重定向输出以更改特定的 csv 列并写入同一文件。逻辑上: awk 'BEGIN{FS=OFS=","} {$19 = $1} 1' a.csv > toSameFile
- c - How do i have my ppinter point to the new string i created
- amazon-web-services - 如何使用分布式模型将 AWS 网络防火墙集成到现有 VPC?
- reactjs - 在 React Web 应用程序的地址栏中键入特定 URL 时无法转到特定 URL