我在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()
当我尝试发送消息时,这是我在IDLE中得到的错误消息:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:Python27liblib-tkTkinter.py", line 1486, in __call__
return self.func(*args)
File "C:UsersUserDesktopthing.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
看起来您稍后确实创建了一个ws实例,在connection()
中,您执行ws = WebSocketApp("ws://echo.websocket.org/", on_message = on_message, on_error = on_error, on_close = on_close)
。只要确保在使用ws
之前完成了这一点,因为这是它被定义的地方。