我想让自己的终端与Tkinter一起完全控制终端中发生的一切。我的问题是我不知道如何监听用户按ENTER键向程序发送命令,以便程序可以执行输入的命令。我搜索了互联网,但我找不到解决方案。所以我想要的是通过一个输入框向一个变量发送一个字符串值,这样程序就可以处理变量,只需按一下ENTER键。有一个简单的解决方案吗?到目前为止这是我的代码:
#Needed modules in the future
import time, os, sys, logging
from pynput import *
from tkinter import *
#The variable that stores the input
userin = ''
#Creating window
root = Tk()
root.geometry('1080x660')
root.title('Terminal')
root.configure(bg="black")
#Making my entrybox
Entry(root, textvariable=userin, fg='lime', bg='black').grid()
#The regular mainloop :)
root.mainloop()
你遗漏了三件事:保存了对Entry
的引用(或者是StringVar
,但在这种情况下不是必需的),一个用于输入键的绑定,以及一个对你想要做的任何事情的函数。这个小部件。
更改此行,这将生成Entry
小部件但无法引用它:
Entry(root, textvariable=userin, fg='lime', bg='black').grid()
对此:
e = Entry(root, textvariable=userin, fg='lime', bg='black')
e.grid()
def process(event=None):
content = e.get() # get the contents of the entry widget
print(content) # for example
# bind enter key (called return in tkinter) to the entry widget and
# connect it to the process function
e.bind('<Return>', process)