Python 为什么Tkinter 1/4中的空白图像是我指定的大小?
我正在使用Tkinter在Python程序中创建画布,并在其中放置一个纯色单色图像。(我需要一个图像,因为稍后我将用另一个图像替换该图像,这就是为什么我不只是指定背景。) 我指定了画布的大小,并在窗口打开时进行了检查。是640x640。我指定空白灰度图像为相同大小,但它以3x320的形式出现,只填充画布的四分之一。 我知道我可以将图像大小更改为1280x1280,这样整个画布将是灰色的,但是当我向画布添加其他图像时,我不想遇到类似的问题 节目如下:Python 为什么Tkinter 1/4中的空白图像是我指定的大小?,python,tkinter,Python,Tkinter,我正在使用Tkinter在Python程序中创建画布,并在其中放置一个纯色单色图像。(我需要一个图像,因为稍后我将用另一个图像替换该图像,这就是为什么我不只是指定背景。) 我指定了画布的大小,并在窗口打开时进行了检查。是640x640。我指定空白灰度图像为相同大小,但它以3x320的形式出现,只填充画布的四分之一。 我知道我可以将图像大小更改为1280x1280,这样整个画布将是灰色的,但是当我向画布添加其他图像时,我不想遇到类似的问题 节目如下: #!/usr/bin/python impo
#!/usr/bin/python
import datetime
import os
from PIL import Image, ImageTk
import sys
import Tkinter as tk
width = 640
height = 640
guiRoot = tk.Tk()
pWindow = tk.Frame(guiRoot)
BlankImage = None
CanvasMap = None
if __name__ == "__main__":
bmpfile = sys.argv[1]
print "Working with file: %s" % bmpfile
BlankImage = ImageTk.PhotoImage(Image.new('RGB', (width, height), 'gray'))
CanvasMap = tk.Canvas(guiRoot, width=width, height=height)
CanvasMap.create_image(0, 0, image=BlankImage)
CanvasMap.grid(row=0, column=0, columnspan=4) #later it's 4 columns
os.system('''/usr/bin/osascript -e 'tell app "Finder" to set frontmost of process "Python" to true' ''')
guiRoot.mainloop()
当它运行时,它看起来是这样的
为什么图像只有画布的1/4大小?当我对画布和图像使用相同的尺寸时,它们将是相同的大小,我需要做什么不同的事情
显示整个图像,但以画布原点为中心
(0,0)
,这就是为什么您只能看到它的右下角1/4
您需要将显示偏移到画布的中心(宽度//2,高度//2)
,或者将图像句柄设置到左上角
以下是一种方法:
import datetime
import os
from PIL import Image, ImageTk
import sys
import Tkinter as tk
width = 640
height = 640
guiRoot = tk.Tk()
pWindow = tk.Frame(guiRoot)
BlankImage = None
CanvasMap = None
if __name__ == "__main__":
bmpfile = sys.argv[1]
# print "Working with file: %s" % bmpfile
BlankImage = ImageTk.PhotoImage(Image.new('RGB', (width, height), 'gray'))
CanvasMap = tk.Canvas(guiRoot, width=width, height=height)
CanvasMap.create_image(width//2, height//2, image=BlankImage)
CanvasMap.grid(row=0, column=0, columnspan=4) #later it's 4 columns
os.system('''/usr/bin/osascript -e 'tell app "Finder" to set frontmost of process "Python" to true' ''')
guiRoot.mainloop()
我知道这必须是相当简单的事情。非常感谢。