Python:deadloop之非模态交互界面(模态循环)(哨兵循环)
deadloop之非模态交互界面(模态循环)(哨兵循环)
通过无限循环,条件退出,实现多模态的交互界面
主要功能1:通过键盘按键g\w\r\b进行界面颜色改变,按q退出
主要功能2:点击界面某处生成输入框,回车使输入框内的文字固定在界面
当等待一个特殊的键入时可用,(以return
为例)
while win.getkey() != 'Return':
pass
#我的菜鸡简略版本
from graphics import *
win = GraphWin('Click and Type', 500, 500)
while True:
keyout = win.checkKey()
if keyout == 'q':
break
elif keyout == 'r':
win.setBackground('pink')
elif keyout == 'w':
win.setBackground('white')
elif keyout == 'b':
win.setBackground('lightblue')
elif keyout == 'g':
win.setBackground('lightgray')
pt = win.checkMouse()
if pt:
entry = Entry(pt, 5)
entry.draw(win)
while True:
key = win.checkKey()
if key == 'Return':
break
elif key:print(key)
entry.undraw()
text = entry.getText()
Text(pt, text).draw(win)
# 教材版本(不同功能函数定义调用)
# event_loop2.py --- color-changing window
from graphics import *
def handleKey(k, win):
if k == 'r':
win.setBackground('pink')
elif k == 'w':
win.setBackground('white')
elif k == 'g':
win.setBackground('lightgray')
elif k == 'b':
win.setBackground('lightblue')
def handleClick(pt, win):
# create an Entry for user to type in
entry = Entry(pt, 10)
entry.draw(win)
# Go modal: loop until user types <Enter> key
while True:
key = win.getKey()
if key == 'Return': break
else:print(key)
# undraw the entry and create and draw Text.
entry.undraw()
typed = entry.getText()
Text(pt, typed).draw(win)
# clear (ignore) ang mouse click that occurred during text entry
win.checkMouse()
def main():
win = GraphWin('Click and Type', 500, 500)
# Event loop: handle presses and mouse clicks until the user
# press the 'q' key.
while True:
key = win.checkKey()
if key == 'q': # loop exit
break
if key:
handleKey(key, win)
pt = win.checkMouse()
if pt:
handleClick(pt, win)
win.close()
main()
运行效果:
moyutime:本文仅是学习心得,观点仅供参考,祝愿读者学习途中快乐且不断有所收获。