导致退格键击的 Python 代码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18320431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:28:29  来源:igfitidea点击:

Python code to cause a backspace keystroke?

pythonkeystrokebackspace

提问by aescript

I keep finding ways to map the backspace key differently, but that's not what I'm after.

我一直在寻找以不同方式映射退格键的方法,但这不是我所追求的。

I'm in a program writing a python code, and basically I want to write a line of code that causes the program to think someone just hit the Backspace key in the GUI (as the backspace key deletes something)

我正在编写 python 代码的程序中,基本上我想编写一行代码,使程序认为某人只是在 GUI 中按下了退格键(因为退格键会删除某些内容)

How I would code in a backspace key stroke?

我将如何在退格键击中编码?

采纳答案by Brent Washburne

The character for backspace is '\b'but it sounds like you want to affect the GUI.

退格的字符是,'\b'但听起来您想影响 GUI。

if your program changes the GUI, then simply delete the last character from the active input field.

如果您的程序更改了 GUI,则只需从活动输入字段中删除最后一个字符即可。

回答by Jiminion

foo = "abc"
foo = foo + "\b" + "xyz"
print foo
>> abxyz
print len(foo)
>> 7

if key == '\b': delete_selected_points()

回答by Thanasis Valto Kourpetis

and i got it !

我明白了!

print('\b ', end="", flush=True) 
sys.stdout.write('0')

it backspace !

它退格!

回答by Joseph Sheedy

As other answers have said, use '\b' to backspace. The trick in your case is to use sys.stdout.write instead of print to not get a newline appended. Then wait and print the appropriate number of backspace characters.

正如其他答案所说,使用 '\b' 退格。您的情况的技巧是使用 sys.stdout.write 而不是 print 来不附加换行符。然后等待并打印适当数量的退格字符。

import time
import sys

print("Good morning!")
while True:
    time_fmt = "It's %I:%M:%S %p on %A, %b %d, %Y"
    time_str = time.strftime(time_fmt)
    sys.stdout.write(time_str)
    sys.stdout.flush()
    time.sleep(1)
    sys.stdout.write("\b"*len(time_str))