繁体   English   中英

Python在Tkinter中发送WebSocket消息

[英]Python send websocket message in tkinter

我在python 2.7上的tkinter中发送websocket消息时遇到问题。 我现在有Tkinter的和WebSocket的客户在一个线程中运行,因此它们都同时循环工作,因为看到这里 问题是,每当我尝试键入消息并按发送按钮时,都会收到NameError。 我正在使用的websocket客户端在这里

这是我的代码:

from Tkinter import *
from websocket import *
from threading import *

master = Tk()
master.wm_title("Websocket Test")
minwidth = master.winfo_screenwidth()/4*3
minheight = master.winfo_screenheight()/4*3
master.minsize(width=minwidth, height=minheight)
master.resizable(0,0)

def sendmsg():
   msg = entry.get()
   ws.send(msg)
   return

text = Text(master)
text.pack(side=TOP, expand=True,fill=BOTH)
entry = Entry(master)
entry.pack(side=BOTTOM, expand=True, fill=BOTH)
button = Button(master, text="SEND", command=sendmsg)
button.pack(side=BOTTOM, expand=True, fill=BOTH)

def on_message(ws, message):
   text.insert(END, "Received: "+message+"\n")
   print "Received: "+message
   return

def on_error(ws, error):
   text.insert(END, error+"\n")
   print error
   return

def on_close(ws):
   text.insert(END, "### closed ###\n")
   print "### closed ###"
   return

def on_open(ws):
   ws.send("hello")
   ws.send("testing")
   return

def connection():
   enableTrace(True)
   ws = WebSocketApp("ws://echo.websocket.org/", on_message = on_message, on_error = on_error, on_close = on_close)
   ws.on_open = on_open

   ws.run_forever()
   return

t = Thread(target=connection)
t.start()

master.mainloop()

这是我每次尝试发送消息时都会收到的错误消息:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1486, in __call__
    return self.func(*args)
  File "C:\Users\User\Desktop\thing.py", line 14, in sendmsg
    ws.send(msg)
NameError: global name 'ws' is not defined

我认为这与线程有关,但是我不确定是什么引起了问题。 websocket on_open函数使用ws.send()成功将消息发送到服务器,但sendmsg函数没有。 感谢所有帮助,因为我是线程技术的新手。

那是因为你

def sendmsg():
    msg = entry.get()
    ws.send(msg)
    return

您需要首先实例化websocket:

def sendmsg():
    ws = WebSocketApp("ws://echo.websocket.org/", on_message = on_message, on_error = on_error, on_close = on_close)
    msg = entry.get()
    ws.send(msg)
    return

看起来您稍后会在connection()创建一个ws实例,然后执行ws = WebSocketApp("ws://echo.websocket.org/", on_message = on_message, on_error = on_error, on_close = on_close) 只需确保在使用ws之前已完成此操作,因为这是定义它的地方。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM