したいですraw_input('Enter something: .')
。3秒間スリープさせ、入力がない場合はプロンプトをキャンセルして残りのコードを実行します。次に、コードがループしてraw_input
再度実装します。また、ユーザーが「q」などを入力すると壊れるようにしたいです。
4 に答える
スレッドを使用しない (少なくとも明示的ではない) 簡単な解決策があります。
import sys
from select import select
timeout = 10
print "Enter something:",
rlist, _, _ = select([sys.stdin], [], [], timeout)
if rlist:
s = sys.stdin.readline()
print s
else:
print "No input. Moving on..."
Edit[0]: select() の基になる実装にはソケットが必要ですが、 sys.stdin には必要ないため、明らかにこれは Windows では機能しません。@Fookatchu さん、ご連絡ありがとうございます。
Windows で作業している場合は、次のことを試すことができます。
import sys, time, msvcrt
def readInput( caption, default, timeout = 5):
start_time = time.time()
sys.stdout.write('%s(%s):'%(caption, default));
input = ''
while True:
if msvcrt.kbhit():
chr = msvcrt.getche()
if ord(chr) == 13: # enter_key
break
elif ord(chr) >= 32: #space_char
input += chr
if len(input) == 0 and (time.time() - start_time) > timeout:
break
print '' # needed to move to next line
if len(input) > 0:
return input
else:
return default
# and some examples of usage
ans = readInput('Please type a name', 'john')
print 'The name is %s' % ans
ans = readInput('Please enter a number', 10 )
print 'The number is %s' % ans
tkinter エントリ ボックスとボタンを備えたカウントダウン アプリを作成するコードがいくつかあるので、何かを入力してボタンを押すことができます。タイマーが切れると、tkinter ウィンドウが閉じて、時間がなくなったことを伝えます。この問題に対する他のほとんどの解決策には、ポップアップするウィンドウがないと思うので、IDをリストに追加すると思いました:)
raw_input() または input() を使用すると、入力セクションで停止するため、入力を受け取るまでは不可能であり、その後続行します...
次のリンクからいくつかのコードを取得しました: Making a countdown timer with Python and Tkinter?
この問題に対する Brian Oakley の回答を使用し、エントリ ボックスなどを追加しました。
import tkinter as tk
class ExampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
def well():
whatis = entrybox.get()
if whatis == "": # Here you can check for what the input should be, e.g. letters only etc.
print ("You didn't enter anything...")
else:
print ("AWESOME WORK DUDE")
app.destroy()
global label2
label2 = tk.Button(text = "quick, enter something and click here (the countdown timer is below)", command = well)
label2.pack()
entrybox = tk.Entry()
entrybox.pack()
self.label = tk.Label(self, text="", width=10)
self.label.pack()
self.remaining = 0
self.countdown(10)
def countdown(self, remaining = None):
if remaining is not None:
self.remaining = remaining
if self.remaining <= 0:
app.destroy()
print ("OUT OF TIME")
else:
self.label.configure(text="%d" % self.remaining)
self.remaining = self.remaining - 1
self.after(1000, self.countdown)
if __name__ == "__main__":
app = ExampleApp()
app.mainloop()
私が追加したのは少し怠け者だったことは知っていますが、それは機能し、単なる例です
このコードは、Pyscripter 3.3 を搭載した Windows で機能します。
rbp の回答:
キャリッジ リターンに等しい入力を考慮するには、ネストされた条件を追加するだけです。
if rlist:
s = sys.stdin.readline()
print s
if s == '':
s = pycreatordefaultvalue