【发布时间】:2020-07-04 17:48:32
【问题描述】:
我是使用 Tkinter GUI 的新手,在尝试制作交互式程序时卡住了 1) 在 GUI 中征求用户的反馈,2) 等待用户响应并按 Enter,3) 然后使用输入以通知主脚本中的后续步骤。
但是,我无法正确执行第 2 步。在函数调用 waitforinput() 中,我希望主脚本在继续执行测试打印输出的下一行之前等待。相反,它使用 '' 作为结果打印主脚本测试行,然后放置一个有效的输入框。为什么这个程序在waitforinput函数完成之前就移动到下一行?谢谢!
import tkinter as tk
from tkinter import *
import threading, time
# assignments for input thread
WAIT_DELAY = 250 #milliseconds
lock = threading.Lock() # Lock for shared resources.
finished = False
result = ''
# Set up the graphical interface
root = tk.Tk(className='My Flashcards')
def main():
# request and wait for input from user
waitforinput()
Test = tk.Label(root, text = "result = " + result)
Test.pack()
Test.config(font = ('verdana', 24), bg ='#BE9CCA')
# sets background thread for getinput from user
def waitforinput():
global finished
with lock:
finished = False
t = threading.Thread(target=getinput)
t.daemon = True
root.after(WAIT_DELAY, check_status) # start waiting
t.start()
# checks to see if user has inputted
def check_status():
with lock:
if not finished:
root.after(WAIT_DELAY, check_status) # keep waiting
# solicits and returns a string from the user
def getinput():
# declaring string variable for storing name and password
answer_var = tk.StringVar()
# define a function that will get the answer and return it
def user_response(event = None):
answer = answer_entry.get()
global result
result = answer
global finished
finished = True # to break out of loop
# creating an entry for inputting answer using widget Entry
answer_entry = tk.Entry(root, width = 1, borderwidth = 5, bg ='#BE9CCA', textvariable = answer_var) ## could be global with args
# making it so that enter calls function
answer_entry.bind('<Return>', user_response)
# placing the entry
answer_entry.pack()
answer_entry.focus()
main()
root.mainloop()
'''
【问题讨论】:
标签: python multithreading tkinter