【发布时间】:2011-01-01 15:06:37
【问题描述】:
我正在开发简单的 GUI,但我被困住了。这是基本流程:
- 显示文本
text和:- 节省时间
time_pressed - 启动
progressbar并更新它,直到time_notallow过期。
- 节省时间
- 如果用户按下
<Next>,查看time_notallow中指定的秒数是否已过, 如果没有,则不允许显示下一个text。
基本上,我想阻止用户调用绑定到<Right> 键的方法,直到time_notallow 通过,并显示一个进度条来通知他们需要等待多长时间。由于我用的是bind,比如……
self.master.bind('<Right>', self.text_next)
...我没有.after(),就像在小部件中一样。
我尝试过的
-
master.after()将bind设置为None并在time_notallow之后将bind设置为self.text_next,但它不起作用。 - 创建了一个
thread,它与while True循环,以不断检查time_notallow是否通过,但应用程序崩溃。
任何帮助表示赞赏。
编辑:一个解决方案。在 .after 中使用 lambda() 来计算秒数(感谢 Bryan Oakley)
"""
Stripped-down version to figue out time/event/threading stuff.
What this has to do:
1. Show the window and some text.
2. User presses Next arrow and new text shows. Paint the label red.
3. Prevent user form pressing again (unbind all keys), until 2 seconds passed
(time_wait).
4. Make notice of passed time and after 2 seconds bind the keys again and
paint the label green.
5. Loop the steps 2-4.
"""
import sys
import tkinter as tk
from tkinter import W, E, S, N
class Test(tk.Frame):
def __init__(self, master=None):
"""Draw the GUI"""
tk.Frame.__init__(self, master)
self.draw_widgets()
self.grid()
self.time_wait = 2
self.locked = False
self.bind_keys()
self.counter = 0
def draw_widgets(self):
"""Draw all the widgets on the frame."""
text = 'Just a sample sentence.'
#Label with the sentence
self.lbl_text = tk.Label(self, anchor="center", relief='groove')
self.lbl_text['text'] = text
self.lbl_text['font'] = ('Helvetica', 27)
self.lbl_text.grid(column=0, row=0, sticky=W+E+S+N)
self.lbl_note = tk.Label(self, anchor="center", relief='groove',
bg='green')
self.lbl_note.grid(column=0, row=1, sticky=W+E+S+N)
def text_next(self, event):
"""Get next text"""
if not self.locked:
self.counter += 1
self.lbl_text['text'] = 'The text number %s!' % self.counter
self.bind_tonone()
self.lock(self.time_wait)
def text_previous(self, event):
"""Get previous text"""
if not self.locked:
self.counter -= 1
self.lbl_text['text'] = 'The text number %s!' % self.counter
self.bind_tonone()
self.lock(self.time_wait)
def bind_keys(self):
"""Bind the keys"""
self.master.bind('<Left>', self.text_previous)
self.master.bind('<Right>', self.text_next)
self.master.bind('<Escape>', self.exit)
self.lbl_note['bg'] = 'green'
def bind_tonone(self):
"""Unbind the keys"""
self.master.bind('<Left>', None)
self.master.bind('<Right>', None)
self.master.bind('<Escape>', None)
self.lbl_note['bg'] = 'red'
def lock(self, n):
if n == 0:
self.locked = False
self.lbl_note['text'] = ''
self.lbl_note['bg'] = 'green'
else:
self.locked = True
self.lbl_note['text'] = 'Locked for %s more seconds' % n
self.lbl_note.after(1000, lambda n = n - 1: self.lock(n))
def exit(self, event):
"""Exit the program."""
sys.exit()
def start():
"""Start the gui part."""
root = tk.Tk()
app = Test(master=root)
app.mainloop()
if __name__ == '__main__':
start()
【问题讨论】:
标签: python events time tkinter bind