python-3.x - 在 Tkinter 中查看需要用户输入的功能并与之交互
问题描述
我正在使用 Tkinter 创建一个应用程序,对于该应用程序,我需要在需要用户输入的包中使用一个函数。我试图sys.stdout
在一个线程中使用并输出sys.stdout
到一个Listbox()
这适用于我的另一个功能做同样的事情,但没有任何用户输入。在该线程的第一行中,我正在更改一个按钮然后执行操作,并且该按钮没有更改并且应用程序进入无响应状态。我的问题是sys.stdout
发送输入要求的内容吗?以及当函数仍在线程中运行时,如何将用户输入从输入框发送到函数?提前感谢以下截断代码:
class Login(tk.Frame):
def __init__(self,parent,controller):
tk.Frame.__init__(self,parent)
global Key
global button1
Key = tk.StringVar()
#Buttton to start thread
button1 = ttk.Button(self, text='Login',command=lambda:Setupthread2(lbx,button1,Key,KeyEntry))
button1.pack()
#Entry for user to input
KeyEntry = tk.Entry(self, show= '*', textvariable=Key)
KeyEntry.pack()
scb = tk.Scrollbar(self)
scb.pack(fill='y' ,side='right')
lbx = tk.Listbox(self, yscrollcommand=scb.set)
lbx.pack()
scb.config(command=lbx.yview)
def Setupthread2(object,button1,Key,KeyEntry):
global flag
send_process = threading.Thread(target=callback(object,button1,Key,KeyEntry))
send_process.start()
flag = False
def callback(object,button1,Key,KeyEntry):
#Changing the button so I can use the same button for both starting the tread and to send to sample func
button1.config(text = 'Send Code', command = lambda:SendUsrInput(Key,KeyEntry))
old_stdout = sys.stdout
sys.stdout = StdoutRedirectorLabel(object)
sample()
sys.stdout = old_stdout
#After Output finished set scrollbar to bottom
object.yview_moveto(1.0)
class StdoutRedirectorLabel(object):
def __init__(self,widget):
self.widget = widget
def write(self,text):
self.widget.insert('anchor',text)
# Me trying to send what they type in entry box to function
def SendUsrInput(Key,KeyEntry):
Key = Key.get()
print(Key)
KeyEntry.delete(0,'end')
#Truncated version of the function I need to show console and to send input to
def sample():
usrInput = input('Enter Input to get something Back')
print(usrInput + ' Was my input')
解决方案
因此,在它通过帮助请求用户输入的模块中,我制作了一个 Tk 窗口,使用超时请求输入after()
def sample()
sms_code = loginTimeout()
def loginTimeout():
root = tk.Tk()
sms_code = ''
def get_entry() -> str:
"""Gets and returns the entry input, and closes the tkinter window."""
nonlocal sms_code
sms_code = entry_var.get()
root.destroy()
return sms_code
# Your input box
entry_var = tk.StringVar()
tk.Tk.wm_title(root,'Trading Bot')
tk.Label(root, text='Please Enter the Authorization Code').pack()
tk.Entry(root, textvariable=entry_var).pack()
# A button, or could be an event binding that triggers get_entry()
tk.Button(root, text='Confirm', command=get_entry).pack()
# This would be the 'timeout'
root.after(300000, get_entry)
root.mainloop()
return sms_code
推荐阅读
- python-3.x - pandas first_valid_index() 作为整数键
- python - RandomForestClassifier 抛出错误:一个字段包含逗号分隔值
- java - 获得 250 多个项目,但自定义列表视图不显示任何内容
- batch-file - 为什么 set 命令会抛出错误?
- python - 列表中数对之间的数学运算
- mysql - 每个月如何获取 SUM 和 COUNT 数据?
- marklogic - MarkLogic 数据中心流升级
- javascript - 如何在制表器中动态实现嵌套表
- grails - 在 Groovy 中使用 SendGrid 发送邮件 - Grails
- android - 在片段中显示多个 ImageView 的最佳方式是什么?