首页 > 解决方案 > 在 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')

标签: python-3.xtkinterinputpython-multithreadingsys

解决方案


因此,在它通过帮助请求用户输入的模块中,我制作了一个 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

推荐阅读