图像调整大小在Tkinter中的PhotoImage上不起作用

时间:2018-06-20 09:19:46

标签: python python-3.x image tkinter

我正在尝试编写代码以在地图背景图像上显示较小的风矢量图像。唯一的问题是风向矢量大于所需的矢量,我想按比例缩小它们。我尝试了subsample(),但是由于某种原因它不起作用,并且图像保持相同大小。

其初始代码如下;

from tkinter import *
root = Tk()
root.title("Click me!")
def next_image(event):
    #toggle between image2 and image3
    global toggle_flag
    global x, y, photo2, photo3
    if toggle_flag == TRUE:
        # display photo2, same center x, y
        canvas1.create_image(x, y, image=photo2)
        toggle_flag = False
    else:
        canvas1.create_image(x, y, image=photo3)
        toggle_flag = True

toggle_flag = True
# pick three GIF image files you have in your working directory
# image1 is larger than image2 and image3
image1 = "Map.png"
photo1 = PhotoImage(file=image1)
image2 = "icons8-wind-speed-43-47-50.png"
photo2 = PhotoImage(file=image2)
photo2.subsample(50)
image3 = "icons8-wind-speed-103-107-50.png"
photo3 = PhotoImage(file=image3)
photo3.subsample(50)
# make canvas the size of image1/photo1
width1 = photo1.width()
height1 = photo1.height()
canvas1 = Canvas(width=width1, height=height1)
canvas1.pack()
# display photo1, x, y is center (anchor=CENTER is default)
x = (width1)/2.0
y = (height1)/2.0
canvas1.create_image(x, y, image=photo1)
canvas1.bind('<Button-1>', next_image)  # bind left mouse click
root.mainloop()

我在Windows 10和默认的tkinter软件包中使用Python 3.6。 请帮忙。

输出看起来像这样; Output image for given code, showing a wind barb vector over the map.

1 个答案:

答案 0 :(得分:0)

这是我开始接受的答案。感谢j_4321。

from tkinter import *
root = Tk()
root.title("Click me!")
def next_image(event):
    #toggle between image2 and image3
    global toggle_flag
    global x, y, photo2, photo3
    if toggle_flag == TRUE:
        # display photo2, same center x, y
        canvas1.create_image(x, y, image=photo2)
        toggle_flag = False
    else:
        canvas1.create_image(x, y, image=photo3)
        toggle_flag = True

toggle_flag = True
# pick three GIF image files you have in your working directory
# image1 is larger than image2 and image3
image1 = "Map.png"
photo1 = PhotoImage(file=image1)
image2 = "icons8-wind-speed-43-47-50.png"
photo2 = PhotoImage(file=image2)
photo2 = photo2.subsample(50)
image3 = "icons8-wind-speed-103-107-50.png"
photo3 = PhotoImage(file=image3)
photo3 = photo3.subsample(50)
# make canvas the size of image1/photo1
width1 = photo1.width()
height1 = photo1.height()
canvas1 = Canvas(width=width1, height=height1)
canvas1.pack()
# display photo1, x, y is center (anchor=CENTER is default)
x = (width1)/2.0
y = (height1)/2.0
canvas1.create_image(x, y, image=photo1)
canvas1.bind('<Button-1>', next_image)  # bind left mouse click
root.mainloop()