简体   繁体   English

更改现有文本项的文本而无需创建新文本项? Tkinter

[英]Change the text of an existing text item without having to create new text items? Tkinter

So I asked a similar question before but I didn't really get any replies so this is a follow up question on a comment... The code is below and I have no idea how to stop the text from over lapping each other, I tried to delete it before creating a new text but then it just returns an error about coordinates not being correct so I doubt that's the solution. 所以我之前也问过类似的问题,但是我没有得到任何答复,所以这是关于评论的后续问题……代码在下面,我不知道如何阻止文本彼此重叠,我尝试在创建新文本之前将其删除,但随后它仅返回有关坐标不正确的错误,因此我怀疑这是解决方案。 Could someone please help? 有人可以帮忙吗?

fuel = 20
# What happens when you click the space bar
def space(evt):
   # Creates text that tells you the velocity and decreases velocity
   global vy, g, dt, fuel
   f=('Times',36,'bold')
   txt=canvas.create_text(w-100,50,
   text=str(fuel),font=f,fill='white')
   if(fuel<0): return
   fuel -= 1
   canvas.delete(txt)
   canvas.create_text(txt, text=str(fuel))
   vy -= 3*g*dt    
# If space key pressed, the function space happens
root.bind('<space>',space)

Thank you!! 谢谢!!

In your method, you are creating text twice. 在您的方法中,您要创建两次文本。

After your first call, there is already a text item created by 首次通话后,已经有一个文本项由创建

canvas.create_text(txt, text=str(fuel))

If space method gets called again, you will create an extra one and this will keep going on for each call. 如果再次调用space方法,则将创建一个额外的方法,每次调用都会继续进行。

Instead of delete-create text everytime, you can create a single text item in global scope then change its text value using canvas.itemconfig() method. 您可以在全局范围内创建单个文本项,然后使用canvas.itemconfig()方法更改其文本值,而不是每次都删除创建文本。

txt=canvas.create_text(w-100, 50, text=str(fuel), font=f, fill='white')
def space(evt):
    ...
    ...
    canvas.itemconfig(txt, text=str(fuel))

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

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