PySimpleGUI按钮事件在Python代码中不起作用-为什么?

jvlzgdj9  于 2023-06-04  发布在  Python
关注(0)|答案(1)|浏览(424)

为什么按钮事件不能用pysimplegui?
这是我的代码。

import os
import threading
import PySimpleGUI as gui
from rsa_controller import decryptwithPrivatekey, loadPublicKey, loadPrivateKey

id = 0
target_id = 0
prikey = None

def popout(title):
    gui.popup(title)

def read_keys():
    print("Opening key files: " + os.getcwd() + "\\keys\\")
    pubkey = loadPublicKey(os.getcwd() + "\\keys\\public.pem")
    prikey = loadPrivateKey(os.getcwd() + "\\keys\\private.pem")

def recv_msg():
    global target_id
    from main import s
    while True:
        data = s.recv(1024)
        if not data:
            break
        decoded_data = data.decode('utf-8')
        if decoded_data == 'target_connected_Success':
            print("Received message:", decoded_data)
        elif decoded_data.startswith("!+@"):
            target_id = decoded_data[3:]
            window2()
        elif decoded_data == 'target_connect_denied':
            gui.popup('Connection request denied')
        else:
            msg_to_recv = decryptwithPrivatekey(decoded_data, prikey)
            print("Received message:", msg_to_recv)

def window2():
    from main import s
    global target_id
    layout2 = [
        [gui.Text('Connecting with'), gui.Text(str(target_id), key='target_id'), gui.Text("Establishing contact")],
        [gui.Button('Accept and share my public key', key='accept', enable_events=True),
         gui.Button('Deny connection invitation', key='denied', enable_events=True)]
    ]
    window = gui.Window("Connection Request", layout2, finalize=True)
    while True:
        event2, values2 = window.read()
        if event2 == gui.WINDOW_CLOSED:
            break
        if event2 == 'Deny connection invitation':
            print("Connection denied")
            s.send('!x!{}'.format(target_id).encode('utf-8'))
            window.close()
        if event2 == 'Accept and share my public key':
            print("Accepting and sharing public key")
            # Handle the logic for accepting the connection
    window.close()

def start_GUI_progress(id):
    from main import s
    read_keys()
    layout = [
        [gui.Text('Your identification code'), gui.Text(id)],
        [gui.Text('Hint: Please enter the identification code of the person you want to connect to in the input box below and click the Connect button')],
        [gui.Input(key='target_id'), gui.Button('Connect', key='connect')]
    ]
    window = gui.Window("RSA Encrypted Chat Software", layout)
    host = "localhost"
    port = 23333
    s.connect((host, port))
    print(s.recv(1024))
    t_recv = threading.Thread(target=recv_msg)
    t_recv.start()
    s.send(b"__!" + str(id).encode('utf-8'))
    while True:
        event, values = window.read()
        if event is None:
            break
        if event == 'connect':
            print("Client is attempting to connect to: {}".format(values['target_id']))
            message = "_!?{}".format(values['target_id'])
            s.send(message.encode('utf-8'))
    window.close()

我发现第一个窗口是intractivable,但window2成功显示后,我按下它的按钮,什么也没有发生,更重要的是,当window2显示,有一个错误:
线程Thread-1(recv_msg)中出现异常:追溯(最近一次调用):文件“C:\Users\bao\AppData\Local\Programs\Python\Python310\lib\threading.py ",line 1009,in_bootstrap_inner www.example.com()File" C:\Users\bao\AppData\Local\Programs\Python\Python310\lib\threading.py ",line 946,in run self._target(* self._args,self。_kwargs)文件" C:\Users\bao\PycharmProjects\RSAEncryptedChatSoftware\GUIDisplay.py ",line 32,in recv_msg window2()File" C:\Users\bao\PycharmProjects\RSAEncryptedChatSoftware\GUIDisplay.py ",line 46,in window2 window = gui. Window(" Connecting with ",layout2,finalize = True)File" C:\Users\bao\PycharmProjects\RSAEncryptedChatSoftware\venv\lib\site-packages\PySimpleGUI\PySimpleGUI.py ",第9614行,在initself中。Finalize()文件" C:\Users\bao\PycharmProjects\RSAEncryptedChatSoftware\venv\lib\site-packages\PySimpleGUI\PySimpleGUI.py",line 10300,in finalize self.读取(timeout = 1)文件" C:\Users\bao\PycharmProjects\RSAEncryptedChatSoftware\venv\lib\site-packages\PySimpleGUI\PySimpleGUI.py",line 10075,in read results = self._read(timeout = timeout,timeout_key = timeout_key)文件" C:\Users\bao\PycharmProjects\RSAEncryptedChatSoftware\venv\lib\site-packages\PySimpleGUI\PySimpleGUI.py",line 10146,in_read self.Show()文件" C:\Users\bao\PycharmProjects\RSAEncryptedChatSoftware\venv\lib\site-packages\PySimpleGUI\PySimpleGUI.py",line 9886,in * Show StartupTK(self)File" C:\Users\bao\PycharmProjects\RSAEncryptedChatSoftware\venv\lib\site-packages\PySimpleGUI\PySimpleGUI.py",line 16935,in StartupTK window. TKroot mainloop()文件" C:\Users\bao\AppData\Local\Programs\Python\Python310\lib\tkinter* init。py”,第1458行,在mainloop self中。谢谢。mainloop(n)RuntimeError:self.run () File "C:\Users\bao\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run self._target(self._args,self._kwargs) File "C:\Users\bao\PycharmProjects\RSAEncryptedChatSoftware\GUIDisplay.py", line 32, in recv_msg window2() File "C:\Users\bao\PycharmProjects\RSAEncryptedChatSoftware\GUIDisplay.py", line 46, in window2 window = gui.Window("Connecting with", layout2, finalize=True) File "C:\Users\bao\PycharmProjects\RSAEncryptedChatSoftware\venv\lib\site-packages\PySimpleGUI\PySimpleGUI.py", line 9614, ininit**self.Finalize() File "C:\Users\bao\PycharmProjects\RSAEncryptedChatSoftware\venv\lib\site-packages\PySimpleGUI\PySimpleGUI.py", line 10300, in finalize self.Read(timeout=1) File "C:\Users\bao\PycharmProjects\RSAEncryptedChatSoftware\venv\lib\site-packages\PySimpleGUI\PySimpleGUI.py", line 10075, in read results = self._read(timeout=timeout, timeout_key=timeout_key) File "C:\Users\bao\PycharmProjects\RSAEncryptedChatSoftware\venv\lib\site-packages\PySimpleGUI\PySimpleGUI.py", line 10146, in _read self.Show() File "C:\Users\bao\PycharmProjects\RSAEncryptedChatSoftware\venv\lib\site-packages\PySimpleGUI\PySimpleGUI.py", line 9886, in *Show StartupTK(self) File "C:\Users\bao\PycharmProjects\RSAEncryptedChatSoftware\venv\lib\site-packages\PySimpleGUI\PySimpleGUI.py", line 16935, in StartupTK window.TKroot.mainloop() File "C:\Users\bao\AppData\Local\Programs\Python\Python310\lib\tkinterinit.py", line 1458, in mainloop self.tk.mainloop(n) RuntimeError: Calling Tcl from different apartment
进程已完成,退出代码为0

sycxhyv7

sycxhyv71#

layout2 = [
        [gui.Text('Connecting with'), gui.Text(str(target_id), key='target_id'), gui.Text("Establishing contact")],
        [gui.Button('Accept and share my public key', key='accept', enable_events=True),
         gui.Button('Deny connection invitation', key='denied', enable_events=True)]
    ]
if event2 == 'Deny connection invitation':
            print("Connection denied")
            s.send('!x!{}'.format(target_id).encode('utf-8'))
            window.close()
        if event2 == 'Accept and share my public key':
            print("Accepting and sharing public key")
            # Handle the logic for accepting the connection

为按钮定义的键与事件循环中使用的事件不同。

  • 为按钮定义的键:'accept''denied'
  • 事件:'Accept and share my public key''Deny connection invitation'
t_recv = threading.Thread(target=recv_msg)

def recv_msg():
    # ... wrong, try to call `window.write_event_value` to generate an event to call `window2` in main thread.
            window2()
    # ... wrong, try to call `window.write_event_value` to generate an event to call `gui.popup` in main thread.
            gui.popup('Connection request denied')
    # ...

GUI应该在主线程下运行!

相关问题