python-3.x - 在 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 滚动条以及放大和缩小按钮,那就太棒了,如果不是,我会尝试构建一个我自己的功能。谢谢你。
解决方案
您需要保留对图像的引用。
你也应该只使用一个 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()
推荐阅读
- groovy - 如何在 groovy 脚本中返回类成员字符串
- html - 如何通过单击检查 Angular 中的材质复选框?
- mapbox - 如何在 MAPBOX 中调整窗口大小时同时适应边界并设置最大边界?
- javascript - 赛普拉斯安全错误。只能在同源文档上调用 open()
- func - 预期返回“房间”的函数中缺少返回
- excel - SumIf 基于列中的当前月份
- android - 适用于 IOS 和 Android 的跨平台移动 SDK,具有原生反应
- amazon-web-services - 尽管我的替换任务正常,但 CodeDeploy 没有替换我的活动任务
- android - 如何使用 liveData 处理错误
- kentico - 无法加载文件或程序集'Mono.Cecil,版本 = 0.9.6.0;初始化 CMS 应用程序