python - 为什么它不让我删除这个字符串或打包它 python

标签 python string canvas time tkinter

我正在尝试制作一个倒计时到指定时间的计时器,说“单击我”删除提示,然后继续。我试图使用 time.sleep 将提示保持 1 秒,然后将其删除,但它一直给我一个错误,即 string 和 int 都没有命令删除、销毁等。有谁知道为什么会出现此问题。感谢您提前提供的任何帮助

from datetime import datetime
from tkinter import *
import time
tk = Tk()
canvas = Canvas(tk, width=400, height=400)
canvas.pack()

selected_date = datetime(2017,3,24,22,22)
me = Label(tk, font=('Times',45))
me.place(relx=0.5, rely=0.5, anchor=CENTER)
me.pack()

def countdown() :

    s = (selected_date - datetime.now()).seconds 
    me['text']=str(s) + " seconds until click" 
    if s == 0:
         text1 = str(canvas.create_text(200, 200, text="CLICK NOW", font=('Times',45)))

         text1.delete()
         time.sleep(1)


    canvas.after(1000, countdown) 


canvas.after(1000, countdown) 
tk.mainloop()

感谢您提前提供的任何帮助。我不知道为什么它继续给我这个错误

最佳答案

str 没有delete。即使它有一个,因为 str 是不可变对象(immutable对象),它不会就地更改字符串本身。

  • 您需要使用 me['text'] = '' 重置文本以删除倒计时消息。

  • 如果你想使用delete CLICK NOW消息,你需要保存create_text的返回值,并稍后将其传递给canvas.delete方法。

<小时/>
def countdown() :
    s = (selected_date - datetime.now()).seconds 
    me['text']=str(s) + " seconds until click" 
    if s == 0:
        text1 = canvas.create_text(200, 200, text="CLICK NOW", font=('Times',45))
        me['text'] = ''  # to delete count down
        #### If you want to delete the 'CLICK NOW' message in a second,
        #### do the following
        # canvas.after(1000, lambda: canvas.delete(text1))
    else:
        canvas.after(1000, countdown)

顺便说一句,您不需要使用time.sleep

关于python - 为什么它不让我删除这个字符串或打包它 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43011857/

相关文章:

javascript - 上传的 Canvas 图像比其主要来源大得多

python - tomcat是否在运行,python脚本

python - 从轮格式 : "...is not a supported wheel on this platform" 安装 numpy

python - 在字符串 "BANANA"中使用 count 来使用 python 的 str.count() inbuild 函数查找 "ANA"作为子字符串时出现错误

javascript - 使用 Chart.js 在同一页面中显示多个响应式图表

Python Canvas 用鼠标tkinter移动项目

java - 在python子进程中发送字符串作为参数

python - ruby 相当于 python izip_longest

java - 如何在 selenium/Java 中将 WebElement 转换为 'if' 语句的字符串

python - 如何将字符串值格式化为实际字符串