如何在tkinter中停止重叠画布图像

2024-09-18 18:46:10 发布

您现在位置:Python中文网/ 问答频道 /正文

1

我希望在执行与图像相关的命令时,图像会出现,但我得到的是,当执行与图像相关的不同命令时,图像会保留在那里,并且感觉有点松散的重叠

这是密码

from tkinter import *
from PIL import ImageTk,Image
w=Tk()
w.geometry('800x400')
nam=Label(w,text="name of car")
nam.place(x=130,y=50) 
w.configure(bg='#b000ff')
le2=Label(w,text="NUMBER",bg='#6863f6',fg='black',font='comicsansms 10 bold')le2.place(x=0,y=180)
ent2=Entry(w,textvar=StringVar,bg='white',fg='black')
ent2.place(x=70,y=180)
lo = Image.open('F:\\all net downoades\\audier.png')
vo = ImageTk.PhotoImage(lo)
lo4 = Image.open('F:\\all net downoades\\lambo.png')
vo2 = ImageTk.PhotoImage(lo4)
def one():
    cn = Canvas(w, widt=400, height=250)  # n, ne, e, se, s, sw, w, nw, or center
    cn.pack(side=BOTTOM, anchor=E)
    cn.create_image(200,135,image=vo)
#another func
def two():
    cn6 = Canvas(w, widt=400, height=250)  # n, ne, e, se, s, sw, w, nw, or center
    cn6.pack(side=BOTTOM, anchor=E)
    cn6.create_image(200,135,image=vo2)
def both():
    if int(ent2.get()) == 1:
        one()
    elif int(ent2.get()) == 2:
        two()
    else:
        pass
bui=Button(w,text="ok",command=both)
bui.place(x=0,y=100)
w.mainloop()

Tags: textfrom图像imageimport命令defplace
2条回答

无论何时调用one()two(),都不应创建新画布。您应该创建画布一次并将其隐藏,然后更新画布内的图像并在one()two()函数内显示:

def one():
    cn.itemconfigure('image', image=vo)

def two():
    cn.itemconfigure('image', image=vo2)

...
cn = Canvas(w, width=400, height=250, bg='#b000ff', highlightthickness=0)
cn.pack(side=BOTTOM, anchor=E)
cn.create_image(200, 135, image=None, tag='image')

w.mainloop()

试试这样,让我知道

count = 0
def one():
    global cn,count
    count+=1
    if count >1:
        cn6.pack_forget()
    cn = Canvas(w, widt=400, height=250)  # n, ne, e, se, s, sw, w, nw, or center
    cn.pack(side=BOTTOM, anchor=E)
    cn.create_image(200,135,image=vo)
#another func
def two():
    global cn6,count
    count+=1
    if count > 1:
        cn.pack_forget()
    cn6 = Canvas(w, widt=400, height=250)  # n, ne, e, se, s, sw, w, nw, or center
    cn6.pack(side=BOTTOM, anchor=E)
    cn6.create_image(200,135,image=vo2)

相关问题 更多 >