我对python Tkinter相当新。我做了一些谷歌搜索,但无法找到一个好的答案。
我有一个Tkinter GUI,如果通过串口检测到某些命令,它会执行某些功能。我有一个脚本,就像一个名为listener.py
的串口侦听器。我希望这个listener.py
与我的tkinter程序通信并执行一个函数。例如,从下面的代码中,我希望我的listener.py
执行self.Start_Test_Button
。怎么可以这样做?
下面是我的listener.py
代码:
def ReadFromPort(port) :
if os.path.exists(port) :
ser = serial.Serial(
port=port,\
baudrate=9600,\
parity=serial.PARITY_NONE,\
stopbits=serial.STOPBITS_ONE,\
bytesize=serial.EIGHTBITS,\
timeout=0)
#this will store the list
seq = []
count = 1
while True:
time.sleep(1)
for c in ser.read():
seq.append(c)
joined_seq = ''.join(str(v) for v in seq) #Make a string from array
if c == '\n':
received = joined_seq.strip("\n")
received = received.strip('\r')
received = received.strip()
#print received
if "Test" in received :
#print "got it"
#print received
ser.close()
return "GO"
sys.exit()
else :
return "Port Not Found"
- 以下是我的Tkinter代码: -
#!/usr/bin/python
import "whatever needed"
class myThread (threading.Thread):
def __init__(self, name, ser):
threading.Thread.__init__(self)
self.name = name
self.ser = ser
self.buf = ""
class PT_Inline(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
self.geometry("600x400")
self.resizable(1,1)
self.title("Some Title")
self.configure(background = 'white')
#self.attributes('-alpha', 0.5)
Function_Button1 = Tkinter.Button(self, text = "Start Test", fg = "black", bg = 'whitesmoke', width = 15, height = 2, font = "ArialBlack 7 bold roman", command = self.Start_Test_Button)
Function_Button1.place(relx = .6, rely = .8, anchor = "c")
Function_Button1.config(highlightbackground = "black")
Function_Button1.config(highlightthickness = 1)
#Function_Button1.config(state=DISABLED)
def Start_Test_Button_funcs(self) :
self.labelVariable_status.set("Waiting For Command")
port = "/dev/ttyACM1"
Read = ReadFromPort(port)
print Read
if Read == "PortNotFound" :
self.serial_number = "N/A"
fail_message = Read
self.Raise_ERROR(self.serial_number, fail_message)
elif Read == "GO" :
"Do ALL Functions Here"
def Start_Test_Button(self) :
t = threading.Thread(target = self.Start_Test_Button_funcs)
t.start()
if __name__ == "__main__":
app = PT_Inline(None)
app.title('Title')
subprocess.Popen(app.mainloop())