简体   繁体   English

如何在 Python 中逐个字符地删除 Tkinter StringVar?

[英]How can I delete a Tkinter StringVar character by character in Python?

I am new to Python and learning Tkinter now.我是 Python 的新手,现在正在学习 Tkinter。 I am working on a simple calculator and need to define a function for the Erase button in my project to delete the entered number character by character (not just cleaning the entry at once).我正在开发一个简单的计算器,需要为我的项目中的Erase按钮定义一个 function 以逐个字符地删除输入的数字(不仅仅是一次清理条目)。

在此处输入图像描述

You can overwrite your existing string with a string containing all characters except the last one:您可以使用包含除最后一个字符之外的所有字符的字符串覆盖现有字符串:

Example with a Tkinter StringVar: Tkinter StringVar 示例:

import tkinter as tk

root = tk.Tk()
text = tk.StringVar()
text.set('Hello world')
text.set(text.get()[0:-1]) # Hello worl (the "d" was removed)
tk.Label(root, textvariable=text).grid()
root.mainloop()

Example with a simple Python string:一个简单的 Python 字符串示例:

text = "Hello world"
text = text[0:len(text)-1]
print(text) # Hello worl (the "d" was removed)

The method len(text) returns the length of the string, then we read from the first character ( 0 ) up to the penultimate one ( len(text)-1] ) and overwrite the existing string. len(text)方法返回字符串的长度,然后我们从第一个字符 ( 0 ) 读取到倒数第二个字符 ( len(text)-1] ) 并覆盖现有字符串。

As @jasonharper has pointed out, you can replace text[0:len(text)-1] with text[0:-1] , which looks cleaner and has the same practical effect.正如@jasonharper所指出的,您可以将text[0:len(text)-1]替换为text[0:-1] ,这样看起来更干净并且具有相同的实际效果。

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

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