相信有很多在Windows上使用Python的小伙伴都會想過這樣一個問題——Python怎么樣才能在IDLE清屏?IDLE是沒有這樣的功能的。
其實,我們可以擴展IDLE,使得我們在開發和測試的時候更加便利。
今天小編就教大家怎么擴展IDLE,使其支持清屏功能。
-
開始之前,我們必須要知道:
IDLE默認沒有清屏功能,所以我們想要使其可以實現清屏,我們就必須要擴展IDLE。
我們需要下載一個叫ClearWindow.py的擴展文件
如圖
-
其代碼如下:
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_window)
def clear_window2(self, event): # Alternative method
# work around the ModifiedUndoDelegator
text = self.text
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")
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)
小伙伴可以復制以上代碼保存成一個ClearWindow.py文件
同樣,我們也可以到bugs.python.org/file14116/ClearWindow.py去復制保存。
-
我們打開Python的安裝目錄,找到Lib目錄下的idlelib目錄
然后把上面保存的ClearWindow.py拷貝到idlelib目錄下。
找到config-extensions.def配置文件並打開它。
如圖
-
在文件末尾加入以下配置:
[ClearWindow]
enable=1
enable_editor=0
enable_shell=1
[ClearWindow_cfgBindings]
clear-window=<Control-Key-l>
來解釋下什么意思
enable=1
#1為真 意思就是啟用這個擴展
enable_editor=0
#編輯器禁用這個擴展
enable_shell=1
#IDLE Shell啟動擴展
clear-window=<Control-Key-l>
#設置快捷鍵為Ctrl + L
-
此時我們打開Python IDLE Shell
點擊Options,可以看到我們的擴展被成功加載。
同樣,我們可以按下Ctrl + L進行清屏操作。我們還可以通過clear-window=<Control-Key-l>修改快捷鍵,例如修改為ctrl + 3,則是clear-window=<Control-Key-3>
怎么樣,學會沒?點一波關注吧(*^__^*)