首页 > 解决方案 > 在 python tkinter 的弹出窗口中放大图像

问题描述

嗨,有人能解释一下为什么这个代码:

from tkinter import *
from io import BytesIO
import requests
from PIL import Image , ImageTk
def full_dimensions (imag_fs):
    s = Tk()
    img = Label(s, image = imag_fs)
    img.pack()
    s.mainloop()

def mainz ():
    r = Tk ()
    _url = 'https://i.imgur.com/4m7AHVu.gif'
    _img = requests.get(_url)
    if _img.status_code ==200:
        _content = BytesIO(_img.content)
    else:
        _content = 'error.gif'
    _x = Image.open(_content)
    imag_fs = ImageTk.PhotoImage(_x)
    _x.thumbnail((100,100),Image.ANTIALIAS)
    imag = ImageTk.PhotoImage(_x)
    img = Button(r, image = imag, command = lambda:full_dimensions(imag_fs))
    img.grid(column=3,row=1)
    r.mainloop()

mainz()

当我点击按钮时返回这个输出

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python37\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "E:\test_image\prova.py", line 23, in <lambda>
    img = Button(r, image = imag, command = lambda:full_dimensions(imag_fs))
  File "E:\test_image\prova.py", line 7, in full_dimensions
    img = Label(s, image = imag_fs)
  File "C:\Python37\lib\tkinter\__init__.py", line 2766, in __init__
    Widget.__init__(self, master, 'label', cnf, kw)
  File "C:\Python37\lib\tkinter\__init__.py", line 2299, in __init__
    (widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: image "pyimage1" doesn't exist

当单击带有真实尺寸或更大图像的按钮时,我想弹出一个窗口。所以第一个问题是我想了解为什么这段代码不起作用。然后,如果有人可以建议一个可以显示带有图像和导航工具的窗口的模块,例如 y 和 x 滚动条以及放大和缩小按钮,那就太棒了,如果不是,我会尝试构建一个我自己的功能。谢谢你。

标签: python-3.xtkinterpython-imaging-library

解决方案


您需要保留对图像的引用。

你也应该只使用一个 roottk.Tk()和一个mainloop; 您可以使用 显示一个新窗口弹出窗口tk.Toplevel

在此处输入图像描述

import tkinter as tk
from io import BytesIO
import requests
from PIL import Image , ImageTk


def full_dimensions(imag_fs):
    top = tk.Toplevel(root)
    img = tk.Label(top, image=imag_fs)
    img.pack()


def get_image():
    _url = 'https://i.imgur.com/4m7AHVu.gif'
    _img = requests.get(_url)
    if _img.status_code == 200:
        _content = BytesIO(_img.content)
    else:
        _content = 'error.gif'
    print('image loaded')
    return _content


root = tk.Tk()

_content =  get_image()   
_x = Image.open(_content)
imag_fs = ImageTk.PhotoImage(_x)
_x.thumbnail((100, 100), Image.ANTIALIAS)

imag = ImageTk.PhotoImage(_x)
img = tk.Button(root, image=imag, command=lambda: full_dimensions(imag_fs))
img.grid(column=3, row=1)

root.mainloop()

推荐阅读