我创建了一个简短的脚本,以在Tkinter Canvas 元素中显示照片。我将 Canvas 元素的大小调整为与照片相同的大小,但是当我启动窗口时,无论我将窗口扩大多少,通常我只会看到图像的一小部分。
同样,当我打印出我用来设置 Canvas 大小的图像大小时,该大小显示为(922,614),而当我记录鼠标在 Canvas 上的点击时,右下角在某处像(500,300)。我的代码如下。我应该更改什么以使 Canvas 与图像大小相同并完全显示图像?
class AppWindow(Frame):
def __init__(self, parent, list_of_files, write_file):
Frame.__init__(self, parent)
self.parent = parent
...
self.image = None
self.canvas = None
self.index = -1
self.loadImage()
self.initUI()
self.resetCanvas()
def initUI(self):
self.style = Style()
self.style.theme_use("default")
self.pack(fill=BOTH, expand=1)
...
self.canvas = Tkinter.Canvas(self, width = self.image.width(), height = self.image.height())
def loadImage(self):
self.index += 1
img = cv2.imread(self.list_of_files[self.index])
img = cv2.resize(img, (0,0), fx = IMAGE_RESIZE_FACTOR, fy = IMAGE_RESIZE_FACTOR)
b, g, r = cv2.split(img)
img = cv2.merge((r,g,b))
im = Image.fromarray(img)
self.image = ImageTk.PhotoImage(image=im)
def resetCanvas(self):
self.canvas.create_image(0, 0, image=self.image)
self.canvas.place(x = 0, y = 0, height = self.image.height(), width = self.image.width())
这是一个截图,显示照片以及它在Tkinter Canvas 中的呈现方式:
到目前为止,这是我尝试过的操作:
self.canvas = Tkinter.Canvas(self, width = self.image.width()*2, height = self.image.height()*2)
确实使 Canvas 变大(我可以知道,因为我在 Canvas 上有一些绘图功能),但是图像保持相同的小尺寸,没有显示整个图像cv2.imshow()
显示cv2格式的图像时,我看到的是完整图像,所以不是cv2
截断了图像的一部分。 我意识到以上内容并不是一个完整的工作示例。我已经缩减了脚本,现在运行它,我仍然看到相同的问题:
import Tkinter
import Image, ImageTk
from Tkinter import Tk, BOTH
from ttk import Frame, Button, Style
import cv2
import os
import time
import itertools
IMAGE_RESIZE_FACTOR = .3
class AppWindow(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.loadImage()
self.initUI()
def loadImage(self):
img = cv2.imread("w_4131.jpg")
img = cv2.resize(img, (0,0), fx = IMAGE_RESIZE_FACTOR, fy = IMAGE_RESIZE_FACTOR)
b, g, r = cv2.split(img)
img = cv2.merge((r,g,b))
im = Image.fromarray(img)
self.image = ImageTk.PhotoImage(image=im)
def initUI(self):
self.style = Style()
self.style.theme_use("default")
self.pack(fill=BOTH, expand=1)
print "width and height of image should be ", self.image.width(), self.image.height()
self.canvas = Tkinter.Canvas(self, width = self.image.width(), height = self.image.height())
self.canvas.pack()
self.canvas.create_image(0, 0, image=self.image)
def main():
root = Tk()
root.geometry("250x150+300+300")
app = AppWindow(root)
root.mainloop()
if __name__ == '__main__':
main()
最佳答案
当您将图像放置在 Canvas 上的0,0位置时,它指定图像中心的位置,而不是左上角。图像就在那里,只是您只看到右下角。
在创建图像的坐标时添加anchor="nw"
,以代表图像的左上角:
self.canvas.create_image(0, 0, image=self.image, anchor="nw")
至于 Canvas 不是图像的相同大小,我没有看到。该图像似乎完全适合 Canvas 。
关于python - Tkinter Canvas 不会显示整个照片图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32376679/