我正在编写一个程序,我想在每30秒后将数据发送到套接字。
import socket
from Tkinter import *
import tkMessageBox
#from threading import *
import thread
_connect = False
u_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
def conn(IP,PORT):
try:
print 'start'
u_sock.connect((IP, PORT))
print 'success'
_connect = True
except socket.error, (value,message):
if u_sock:
print 'fail'
u_sock.close()
return
def connFunction():
IP = IP_entry.get()
if len(IP) < 7:
tkMessageBox.showinfo("Error", "Invalid IP Address")
return
PORT = int(PORT_entry.get())
print IP , PORT
thread.start_new_thread(conn,(IP, PORT, ))
def SEND():
print 'Send'
if(_connect == True):
print 'sending...'
Inv = 'DATA'
u_sock.send(Inv.decode('hex'))
data = u_sock.recv(4096)
d = data.encode('hex').upper()
print 'Received', repr(d)
GUI = Tk()
GUI.title('RFID')
#GUI.geometry("365x280")
GUI.wm_iconbitmap('RFID.ico')
GUI.columnconfigure(8, pad=3)
GUI.rowconfigure(8, pad=3)
IP_label = Label(GUI,text = "IP Address: ",borderwidth=5)
IP_label.grid(column=0, row=1, sticky=W)
IP_entry = Entry(GUI,width=15,borderwidth=3)
IP_entry.grid(column=3,row=1,sticky=E)
PORT_label = Label(GUI,text = "Port: ",borderwidth=5)
PORT_label.grid(column=8, row=1, sticky=E)
PORT_entry = Entry(GUI,width=6,borderwidth=3)
PORT_entry.grid(column=9,row=1,sticky=E)
Conn_button= Button(GUI,text="Connect",command=connFunction,borderwidth=1,height=1,width=12)
Conn_button.grid(column=16,row=1,padx=10,pady=5,sticky=(W,E))
#GUI.after(1000,SEND)
GUI.mainloop()
我需要每隔30秒调用一次send函数,或者如何创建每30秒后自动调用的事件。我尝试这样做GUI.after(1000,SEND)
但它对我不起作用。它只是第一次调用SEND功能......
请帮我一个例子。感谢
答案 0 :(得分:2)
假设SEND花费不到几百毫秒,请删除线程代码并在之后使用。关键是在内部 SEND
函数后调用,以便自动重复。
def SEND():
print 'Send'
...
GUI.after(30000, SEND)
...
GUI = Tk()
...
SEND()
GUI.mainloop()