问题描述
我正在编写一个程序,我想在每 30 秒后将数据发送到套接字.
I am writing a program in which I want to send data to socket after every 30 seconds.
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 函数...请帮我举个例子.谢谢
I need to call send function after every 30 seconds or how to create the event which is automatically called after every 30 seconds . I try to do this GUI.after(1000,SEND)
but it does not works for me. it calls the SEND function only first time...Kindly Help me out with an example. Thanks
推荐答案
假设 SEND 的时间不到几百毫秒,去掉线程代码,之后使用.关键是在内部之后调用SEND
函数,使其自动重复.
Assuming that SEND takes less than a few hundred milliseconds, remove the threading code and use after. The key is to call after inside the SEND
function so that it auto-repeats.
def SEND():
print 'Send'
...
GUI.after(30000, SEND)
...
GUI = Tk()
...
SEND()
GUI.mainloop()
这篇关于每 30 秒或特定时间间隔后的 Python Tkinter 调用事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!