【问题标题】:How to delete first character of tkinter text widget如何删除 tkinter 文本小部件的第一个字符
【发布时间】:2021-04-26 16:19:22
【问题描述】:

您好,我正在为tkinter 苦苦挣扎。我只是想删除文本小部件的第一个字符,例如单击按钮。我已经看到 [Bryan Oakleys 在这里回答][1] 但不幸的是它对我不起作用。 就像他说的,我是这样尝试的:

text.delete("1.0")

但就像我说的那样,它不起作用。我也没有收到任何错误。它根本不起作用。

from tkinter import *
import time


class TipManager:
    def __init__(self):
        self.root = Tk()
        self.root.attributes("-fullscreen", True)
        self.root.bind("<KeyPress>", self.click)
        self.clicks = 0
        self.chars = []
        self.cps = 0
        self.start = time.time()
        self.average()
        self.text = Text(self.root,tabs=2,font=("Arial", 30))
        self.text.grid(row=0, column=0)
        self.root.mainloop()




    def click(self,e):
        if e.char.isalpha() or e.char == " ":
            self.chars.append(e.char)
            self.clicks += 1
            if len(self.chars) > 15:
                self.text.delete("1.0")
            self.text.configure(state="normal")
            self.text.insert(END, e.char)
            self.text.configure(state="disabled")


        if e.char == "\x7f":
            if not len(self.chars) == 0:
                self.text.configure(state="normal")
                self.text.delete("end-2c")
                self.text.configure(state="disabled")
                del self.chars[-1]

    def average(self):
        self.cps = self.clicks
        print(f"Your average typing speed was {self.cps} c/s")
        self.clicks = 0
        self.root.after(1000, self.average)




tipp_10 = TipManager()

这是我的完整代码 [1]:https://stackoverflow.com/questions/49232866/how-to-delete-last-character-in-text-widget-tkinter#:~:text=The%20index%20END%20represents%20the,(end%20minus%20two%20characters).

【问题讨论】:

  • 请分享您的代码
  • 请发帖minimal reproducible example。我们更喜欢可以复制和粘贴然后运行的东西。
  • @TheLizzard 是的,我试过了,但也没有用
  • @PucciLaCanton 问题是当您尝试删除字符时,tkinter.Text"disabled"。将self.text.configure(state="normal") 移到for 循环之前。
  • 请发布错误。

标签: python tkinter


【解决方案1】:

变化:

if len(self.chars) > 15:
    self.text.delete("1.0")
self.text.configure(state="normal")
self.text.insert(END, e.char)
self.text.configure(state="disabled")

到:

self.text.configure(state="normal")
if len(self.chars) > 15:
    self.text.delete("1.0")
self.text.insert(END, e.char)
self.text.configure(state="disabled")

&lt;tkinter.Text&gt; 的状态必须是 "normal",当您从中 .insert/.delete 时。

【讨论】:

  • 哇,这是我这边的愚蠢错误。谢谢
【解决方案2】:

在您插入/删除文本框之前,请确保您的文本框已启用。所以把self.text.configure(state="normal")放在这行之前:

if len(self.chars) > 15:
self.text.delete("1.0")

【讨论】:

  • 没有,很遗憾没有
  • 下次请尝试查找问题中描述的问题的根本原因。
猜你喜欢
  • 2018-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-11
  • 2018-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多