繁体   English   中英

Python Tkinter 按下按钮旋转已显示的图像

[英]Python Tkinter rotate image already on display with press of a button

我正在尝试旋转 Tkinter window 上的图像,同时按下按钮显示它。 我试图在下面看到的代码中实现它。 当我尝试目录上的代码图像被旋转但显示的图像保持不变时。 谁能帮我这个?

这是我尝试的最后一件事:

import tkinter
from tkinter import *
import cv2
import numpy as np

global rotater
rotater=True
def rotate_img(img_path, rt_degr):
    img = Image.open(img_path)
    return img.rotate(rt_degr, expand=1)

def draw():
    global rotater

    if rotater:
        img_rt_90 = rotate_img("sas.png", 90)
        img_rt_90.save("sas.png")
        label.config(image=image)
        rotater = False
    else:
        img_rt_90 = rotate_img("sas.png", 90)
        img_rt_90.save("sas.png")
        label.config(image=image)
        rotater = True
root = Tk()
image = cv2.imread("sas.png")
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
image = Image.fromarray(image)
image = ImageTk.PhotoImage(image)
label = Label(image=image)
label.pack()
but12=Button(root,text="deneme",command=draw)
but12.pack()
root.mainloop()

这是因为您在draw()中将旧图像分配给 label :

def draw():
    global rotater

    if rotater:
        img_rt_90 = rotate_img("sas.png", 90)
        img_rt_90.save("sas.png")
        label.config(image=image) # <- assigned original image
        rotater = False
    else:
        img_rt_90 = rotate_img("sas.png", 90)
        img_rt_90.save("sas.png")
        label.config(image=image) # <- assigned original image
        rotater = True

您需要分配旋转后的图像,如下所示:

def draw():
    global rotater, image # use global "image"

    if rotater:
        img_rt_90 = rotate_img("sas.png", 90)
        img_rt_90.save("sas.png")
        image = ImageTk.PhotoImage(img_rt_90) # update image with rotated one
        label.config(image=image)
        rotater = False
    else:
        img_rt_90 = rotate_img("sas.png", 90)
        img_rt_90.save("sas.png")
        image = ImageTk.PhotoImage(img_rt_90) # update image with rotated one
        label.config(image=image)
        rotater = True

ifelse块中的内容基本相同,为什么呢?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM