gpt4 book ai didi

python - 在 Tkinter 中替换 Canvas 图像

转载 作者:行者123 更新时间:2023-12-01 08:44:46 26 4
gpt4 key购买 nike

我有一个程序,我希望当有人单击按钮时, Canvas 图像会发生变化。我的代码如下:

from PIL import ImageTk,Image, ImageFont, ImageDraw
import tkinter
import textwrap
from tkinter import Frame, Canvas, Text, INSERT, END


root = tkinter.Tk()
root.geometry("296x337")
root.resizable(False, False)

im=Image.open("red.jpg")
photo=ImageTk.PhotoImage(im)
cv = tkinter.Canvas()
cv.pack(side='top', fill='both', expand='yes')
cv.create_image(0, 0, image=photo, anchor='nw')

def changepic():
###place where I want to change the Canvas Image
print("change color")#I added this because python wouldn't let me run thee function without something.


a2=tkinter.Button(root,text='change color',bd=0, command=changepic)
a2.config(highlightbackground='black')
a2.place(x=135, y=70)

最佳答案

我没有使用 Canvas,而是替换了代码,以便它使用 tkinter.Label 打印图像:

from PIL import ImageTk,Image, ImageFont, ImageDraw
import tkinter
import textwrap
from tkinter import Frame, Canvas, Text, INSERT, END


root = tkinter.Tk()
root.geometry("296x337")
root.resizable(False, False)

img = ImageTk.PhotoImage(Image.open("red.jpg"))
panel = tkinter.Label(root, image=img)
panel.pack(side="bottom", fill="both", expand="yes")

def changepic(imagename):
img2 = ImageTk.PhotoImage(Image.open(imagename))
panel.configure(image=img2)
panel.image = img2


a2=tkinter.Button(root,text='change color',bd=0, command=changepic("blue.jpg")
a2.config(highlightbackground='black')
a2.place(x=135, y=70)

我的信息来自:How to update the image of a Tkinter Label widget?

并且:https://www.tutorialspoint.com/python/tk_label.htm

关于python - 在 Tkinter 中替换 Canvas 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53354959/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com