将 wxpython TextCtrl 与 python 脚本 input() 连接起来

问题描述

我正在研究 python GUI,它可以加密用户的输入并将加密的消息存储在一个文件中。我在尝试将 python 脚本中的 input() 实现到 wxpython GUI 时遇到问题。将不胜感激任何帮助。

下面是我用于加密的python脚本(公钥和私钥是从另一个.py文件生成的):

from Crypto.PublicKey import RSA
from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES,PKCS1_OAEP

data = input("Enter message: ").encode("utf-8")
file_out = open("encrypted_data.bin","wb")

recipient_key = RSA.import_key(open("receiver.pem").read())
session_key = get_random_bytes(16)

# Encrypt the session key with the public RSA key
cipher_rsa = PKCS1_OAEP.new(recipient_key)
enc_session_key = cipher_rsa.encrypt(session_key)

# Encrypt the data with the AES session key
cipher_aes = AES.new(session_key,AES.MODE_EAX)
ciphertext,tag = cipher_aes.encrypt_and_digest(data)
[ file_out.write(x) for x in (enc_session_key,cipher_aes.nonce,tag,ciphertext) ]
file_out.close()

这是我目前在 wxpython GUI 上的工作:

import wx
import subprocess
import os

class MyFrame(wx.Frame):    
    def __init__(self,parent,title):
        super().__init__(parent,title=title)
        self.panel = MyPanel(self)

class MyPanel(wx.Panel):
    def __init__(self,parent): 
        super(MyPanel,self).__init__(parent)
        
        vBox = wx.BoxSizer(wx.VERTICAL)
        hBox = wx.BoxSizer(wx.HORIZONTAL)

        self.genBtn = wx.Button(self,label = "Generate Keys")
        hBox.Add(self.genBtn,wx.EXPAND)
        self.genBtn.Bind(wx.EVT_BUTTON,self.genProc)
        self.SetSizer(hBox)

        self.sendBtn = wx.Button(self,label="Send Message")
        hBox.Add(self.sendBtn,wx.BottOM)
        self.genBtn.Bind(wx.EVT_BUTTON,self.genProc)
        self.SetSizer(hBox)


    def genProc(self,event):
        p = subprocess.Popen(["python","-u","Generate.py"],stdout=subprocess.PIPE,bufsize=-1)
        self.pid = p.pid
        wx.MessageBox("Public and Private Keys Generated",'Dialog',wx.OK | wx.ICON_informatION)
        #wx.MessageBox("Message Box Icon Warning",wx.OK | wx.ICON_WARNING)
        #wx.MessageBox("Message Box Dialog Error",wx.OK | wx.ICON_ERROR)
        
class MyApp(wx.App):
    def OnInit(self):
        self.frame = MyFrame(parent=None,title="Sender")
        self.frame.Show()
        self.SetTopWindow(self.frame)
        return True
        
def main():
    app = MyApp()
    app.MainLoop()

if __name__ == '__main__':
    main()

解决方法

好吧,你需要的是一个简单的绑定:

self.yourtestctrl.Bind(wx.EVT_TEXT_ENTER,self.OnTextEnter)

注意:

要做到这一点,您需要将 wx.TE_PROCESS_ENTER 添加到您的文本控件的样式中

这样做你必须创建你的函数:

def OnTextEnter(self,event):
    
    text = [self.yourtextevetn.GetLineText(line)for line in self.yourtextctrl.GetNumberOfLines()]

    text = "\n".join("text")

    #here you have your input and you can store it o call a function with it

注意:

如果你想让用户在他想要的时候发送输入,你可以创建一个wx.Button,然后将它绑定到上面的函数