我正在尝试为学校制作一个简单的聊天窗口。当我尝试使用entry.get()函数时,它会给出一个错误,每次测试代码时都会更改。 这是脚本:
import socket
import sys
import tkinter
global ready
ready = False
def setready():
global ready
ready = True
window = tkinter.Tk()
window.title("MAGENTA Chat Host v1 - send")
window.geometry("200x100")
window.configure(bg = "magenta")
but = tkinter.Button(window, text = "Send", command = (setready()))
lbl = tkinter.Label(window, bg = "magenta", fg = "snow", text = "Chat")
msgfield = tkinter.Entry(window)
but.pack(side = tkinter.RIGHT)
lbl.pack(side = tkinter.TOP)
msgfield.pack(side = tkinter.LEFT)
message = "Message"
UDP_IP = "127.0.0.1"
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
lbl.config(text = "Socket successfully created")
except socket.error as err:
lbl.config(text = "Socket creation failed with error %s" %(err))
window.mainloop()
while True:
if ready == True:
message = msgfield.get()
if message == "exit":
s.close()
window.destroy()
sys.exit()
else:
s.sendto(bytes(message, "utf-8"),(UDP_IP,5000))
msgfield.select_clear()
ready = False
这是错误:
Traceback (most recent call last):
File "C:\Users\qscguest\Desktop\ChatSend.py", line 33, in <module>
message = msgfield.get()
File "C:\Program Files\Python35\lib\tkinter\__init__.py", line 2522, in get
return self.tk.call(self._w, 'get')
_tkinter.TclError: invalid command name ".55573472"
我怎么这么糟糕?我该如何解决这个问题?
答案 0 :(得分:0)
window.mainloop()
不会退出。尝试引用窗口小部件之后的任何代码都将失败,因为窗口小部件已被销毁。
答案 1 :(得分:0)
我认为你试图让你的tkinter应用程序关闭程序,当你输入exit并点击发送以及做其他功能,如果否则。我修改了你的代码来做我认为你正在尝试的事情。
我换了一些东西。
我摆脱了全局,因为我们可以在循环时将ready
移动到定义的函数。
我更改了按钮以使用lambda运行命令myWhile()
循环,因此启动时不会调用myWhile。
我添加了一个名为myWhile()
的函数来容纳while循环并执行您需要完成的任务。如果这是您正在寻找的,请告诉我,因为我不能100%确定您的需求。
import socket
import sys
import tkinter
window = tkinter.Tk()
window.title("MAGENTA Chat Host v1 - send")
window.geometry("200x100")
window.configure(bg = "magenta")
but = tkinter.Button(window, text = "Send", command = lambda: myWhile())
lbl = tkinter.Label(window, bg = "magenta", fg = "snow", text = "Chat")
msgfield = tkinter.Entry(window)
but.pack(side = tkinter.RIGHT)
lbl.pack(side = tkinter.TOP)
msgfield.pack(side = tkinter.LEFT)
message = "Message"
UDP_IP = "127.0.0.1"
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
lbl.config(text = "Socket successfully created")
except socket.error as err:
lbl.config(text = "Socket creation failed with error %s" %(err))
def myWhile():
ready = True
while ready == True:
message = msgfield.get()
print ('ready')
if message == "exit":
s.close()
window.destroy()
sys.exit()
else:
s.sendto(bytes(message, "utf-8"),(UDP_IP,5000))
msgfield.select_clear()
ready = False
window.mainloop()