【发布时间】:2016-09-17 12:49:09
【问题描述】:
我正在尝试使用 tkinter 创建一个图像查看程序,一切正常,除了:我想要一个用户选择的目录中所有图像的列表,这个列表应该显示在画布上,带有水平滚动条附在它上面,我看到这个页面上的其他人也有同样的问题,有人说使用框架,但当我想使用滚动条时,我收到以下错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.4/tkinter/__init__.py", line 1536, in/
__call__
return self.func(*args)
File "/usr/lib/python3.4/tkinter/__init__.py", line 1549, in xview
res = self.tk.call(self._w, 'xview', *args)
_tkinter.TclError: unknown option "1": must be moveto or scroll
>>>
我无法从中看出端倪,所以请大家帮忙,感谢您的帮助,这里是实际代码:
from tkinter import *
from PIL import Image,ImageTk
import os
import time
#next image
def Next():
i += 1
global img,i
print(i)
display_images(data[i])
#previous image
def Previous():
i -= 1
global img,i
print(i)
display_images(data[i])
#list of images on canvas
def show_images():
global photoButtons,imgFile,imOpen,imgFoto,resized,photolist
j = 0
for number in data:
print(">>>",number)
imOpen.append(Image.open(data[j]))
imgFile.append(imOpen[j])
resized.append(imgFile[j].resize((50,50),Image.ANTIALIAS))
imgFoto.append(ImageTk.PhotoImage(resized[j]))
photoButtons.append(Button(photolist, text=j,/
image=imgFoto[j],command=display_images(data[j]),width=50,/
height = 50))
photoButtons[j].pack(side=RIGHT)
j += 1
#display selected image
def display_images(image_name):
img = Image.open(image_name)
size = img.resize((700,500),Image.ANTIALIAS)
photoviewer.image = ImageTk.PhotoImage(size)
photoviewer.create_image(0,0, image=photoviewer.image,anchor='nw')
# END DEF's
global i
i=0
#root
root = Tk()
#root size
root.geometry("1000x720+0+0")
#canvas for displaying image
photoviewer = Canvas(root, width=700, height=500)
photoviewer.grid(row = 0, column = 0)
photoviewer.place(x=295, y=215,)
#frame (ive got this from another page of stack overflow)
frame=Frame(root,width=300,height=300)
frame.grid(row=0,column=0)
#canvas for displaying list of images
photolist = Canvas(frame, width=395, height=50)
#scrollbar
scrl=Scrollbar(frame,orient=HORIZONTAL)
scrl.pack(side=BOTTOM,fill=X)
scrl.config(command=photolist.xview)
photolist.pack(side=TOP)
imgFile = []
imOpen=[]
imgFoto=[]
resized = []
#get the directory with the images from the user
data = os.listdir()
print(data)
cd = input("change directory to: ")
while cd != "x":
os.chdir(cd)
data = os.listdir()
print(data)
cd = input("change directory to: ")
#end
#creating button for next image
nxt=Button(root,text=">",command= Next)
#creating button for previous image
prvs=Button(root,text="<",command= Previous)
photoButtons = []
show_images()
root.mainloop()
这个想法是用户应该选择一个目录,然后在他们按下“x”后,程序应该调用 show_images,它应该在画布上显示该目录中的所有图像,并附有滚动条,然后用户应该可以在它们之间进行选择,也可以选择下一个和上一个,但是滚动条不起作用。
【问题讨论】:
-
也许你需要
photolist.config(xscrollcommand=scrl.set)。至少我发现的一些例子有这样的线。 -
你的代码有语法错误(以
/结尾的行)
标签: python canvas tkinter scrollbar tkinter-canvas