前言
  在使用 Python IDLE 时,我时常想有没有像命令提示符环境中的 cls 那样的清屏命令,一下子删除交互模式中所有已执行的命令,毕竟每次都关掉再重新打开 IDLE 有点麻烦,于是在网上搜了一下教程,学会了自定义 IDLE 清屏快捷键,觉得很不错,就来分享一下。

点击查看原创

步骤

  1. 新建 ClearWindow.py 文件,粘贴代码到文件
  2. 将该文件内容保存后放入如下文件夹:Python 安装路径中的 D:\Python\Python310\Lib\idlelib 里面(这是我的安装路径)。
  3. 在该路径中找到 config-extensions.def 文件(idle扩展的配置文件);以记事本的方式打开它,在末尾增加代码

ClearWindow.py中的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
"""

Clear Window Extension
Version: 0.2
provides "Clear Shell Window" under "Options"
with ability to undo.
Add these lines to config-extensions.def

[ClearWindow]
enable=1
enable_editor=0
enable_shell=1
[ClearWindow_cfgBindings]
clear-window=<Control-Key-l>


"""

class ClearWindow:

menudefs = [
('options', [None,
('Clear Shell Window', '<<clear-window>>'),
]),]

def __init__(self, editwin):
self.editwin = editwin
self.text = self.editwin.text
self.text.bind("<<clear-window>>", self.clear_window2)

self.text.bind("<<undo>>", self.undo_event) # add="+" doesn't work

def undo_event(self, event):
text = self.text

text.mark_set("iomark2", "iomark")
text.mark_set("insert2", "insert")
self.editwin.undo.undo_event(event)

# fix iomark and insert
text.mark_set("iomark", "iomark2")
text.mark_set("insert", "insert2")
text.mark_unset("iomark2")
text.mark_unset("insert2")


def clear_window2(self, event): # Alternative method
# work around the ModifiedUndoDelegator
text = self.text
text.undo_block_start()
text.mark_set("iomark2", "iomark")
text.mark_set("iomark", 1.0)
text.delete(1.0, "iomark2 linestart")
text.mark_set("iomark", "iomark2")
text.mark_unset("iomark2")
text.undo_block_stop()
if self.text.compare('insert', '<', 'iomark'):
self.text.mark_set('insert', 'end-1c')
self.editwin.set_line_and_column()

def clear_window(self, event):
# remove undo delegator
undo = self.editwin.undo
self.editwin.per.removefilter(undo)

# clear the window, but preserve current command
self.text.delete(1.0, "iomark linestart")
if self.text.compare('insert', '<', 'iomark'):
self.text.mark_set('insert', 'end-1c')
self.editwin.set_line_and_column()

# restore undo delegator
self.editwin.per.insertfilter(undo)


config-extensions.def文件末尾新增的代码

1
2
3
4
5
6
[ClearWindow]
enable=1
enable_editor=0
enable_shell=1
[ClearWindow_cfgBindings]
clear-window=<Control-Key-w>

到这里就可以保存关闭了,再重新打来 IDLE 窗口就可以发现Options下多了个选项即为清屏快捷键。

【注】我这里设置的快捷键是Ctrl+W,这个快捷键是可以任意修改的,修改的方法就是在上面配置代码的最后一行“ clear-window=”,将其中的 “w” 改为其他字符就行,但必须是小写字母。使用快捷键的时候,注意键盘要在英文小写的状态下