python - 简单的图像查看器

标签 python tkinter python-imaging-library

我是这个网站的新手,我正在尝试使用 Tkinter 在 Python 2.7 中创建一个简单的图像查看器,但是当我尝试在其中加载图像时,它没有显示任何内容!我敢打赌这是一件令人尴尬的事情很明显,但我不知道出了什么问题。我正在使用 Windows XP。这是我的代码:

from Tkinter import *
import tkFileDialog
from PIL import ImageTk, Image

root = Tk(className="Image viewer")

canvas_width = 800
canvas_height = 600
root.config(bg="white")

def openimage():
    picfile = tkFileDialog.askopenfilename()
    img = ImageTk.PhotoImage(file=picfile)
    canvas.create_image(0,0, anchor=NW, image=img) 

yscrollbar = Scrollbar(root)
yscrollbar.pack(side=RIGHT, fill=Y)

xscrollbar = Scrollbar(root, orient=HORIZONTAL)
xscrollbar.pack(side=BOTTOM, fill=X)

canvas = Canvas(root, width=canvas_width, height=canvas_height, yscrollcommand=yscrollbar.set, xscrollcommand=xscrollbar.set)
button = Button(root,text="Open",command=openimage)
button.pack(side=BOTTOM)
canvas.pack(side=TOP)
yscrollbar.config(command=canvas.yview)
xscrollbar.config(command=canvas.xview)

mainloop()

更新:当我删除文件浏览器并为其提供文件路径时它可以工作,但我想要文件浏览器并使用标签工作,但滚动条不能使用它,我希望能够滚动图片。

最佳答案

我在“The Tkinter PhotoImage Class”上发现无法将 PhotoImage 分配给函数中的局部变量,因为垃圾收集器将其删除。

所以你可以使用全局变量:

img = None

def openimage():
    global img

    picfile = tkFileDialog.askopenfilename()
    img = ImageTk.PhotoImage(file=picfile)
    canvas.create_image(0,0, anchor=NW, image=img) 

或将图像分配给现有的小部件(例如canvas)

def openimage():
    picfile = tkFileDialog.askopenfilename()
    canvas.img = ImageTk.PhotoImage(file=picfile)
    canvas.create_image(0,0, anchor=NW, image=canvas.img) 

顺便说一下:你应该检查文件是否被选中

def openimage():
    picfile = tkFileDialog.askopenfilename()
    if picfile:
        canvas.img = ImageTk.PhotoImage(file=picfile)
        canvas.create_image(0,0, anchor=NW, image=canvas.img) 

添加scrollregion,你就有了带工作滚动条的文件查看器

def openimage():
    picfile = tkFileDialog.askopenfilename()
    if picfile:
        canvas.img = ImageTk.PhotoImage(file=picfile)
        canvas.create_image(0,0, anchor=NW, image=canvas.img) 
        canvas.configure(canvas, scrollregion=(0,0,canvas.img.width(),canvas.img.height()))

关于python - 简单的图像查看器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19918393/

相关文章:

用于在某些两个字符串之间提取字符串的 python 正则表达式

python - Canvas 中的 Tkinter 窗口不会填充其父级的高度

python - 修改 Tkinter 条目小部件时如何获取事件回调?

python - 滚动条从 Tkinter Canvas 中消失,并拒绝坚持侧面包装

python - 使用 python/PIL 自动裁剪图像

python - 使用 PIL,我可以以可定制的方式组合两个(或更多)波段吗?

python - libjpeg.so.62 : cannot open shared object file: No such file or directory

python - 有没有更好/更有效的方法来做到这一点(矢量化)? Pandas apply 性能非常慢

python - OSx 更新后如何修复损坏的 python 2.7.11

python - 无法修改我的脚本来限制抓取时的请求数量