【发布时间】:2018-04-18 15:48:04
【问题描述】:
我编写了一个 Arduino 代码,它对按钮和物理交互做出反应,然后将结果发送到运行我的 python 程序 (2.7) 的计算机。 python代码有两个功能:
- 新建一个以unixtimestamp命名的文本文件并填充 以及它收到的所有数据。
- 查看它收到的代码短语
"a1"和"b1"的数据 然后显示相应的图像。
当 Arduino 启动时,它将发送 "a1" 作为第一个值来填充窗口。之后,它应该根据它发送的数据进行切换。
这是我当前的代码:
from Tkinter import *
from random import *
import serial
import time
root = Tk()
prompt = StringVar()
root.title("vision")
label = Label(root, fg="dark green")
label.pack()
frame = Frame(root,background='red')
frame.pack()
canvas = Canvas(height=200,width=200)
canvas.pack()
timestamp = int(time.time())
filename=str(timestamp)+".txt"
f = open(str(filename),"w")
f.write("\n")
f.write(str(filename))
f.write("\n")
arduino = serial.Serial('COM5', 115200, timeout=.1)
while True:
data = arduino.readline()[:-2] #the last bit gets rid of the new-line chars
print data
f.write(str(data))
f.write("\n")
#Invoking through button
TextWindow = Label(frame,anchor = NW, justify = LEFT, bg= 'white', fg = 'blue', textvariable = prompt, width = 75, height=20)
TextWindow.pack(side = TOP)
if data == "a1":
canvas.delete("all")
image1 = PhotoImage(file = "c2.gif")
canvas.create_image(0,0,anchor='nw',image=image1)
canvas.image = image1
if data == "b1":
canvas.delete("all")
image1 = PhotoImage(file = "c2.gif")
canvas.create_image(0,0,anchor='nw',image=image1)
canvas.image = image1
root.mainloop()
它生成窗口但它是空的。 我似乎找不到我的错误在哪里。
另外: 我使用了另一个教程,它为我提供了 gui 和图像的基本代码。其中有两个按钮可以切换有效的图像。
from Tkinter import *
from random import *
pathy = randint(1, 2)
root = Tk()
prompt = StringVar()
root.title("vision")
label = Label(root, fg="dark green")
label.pack()
frame = Frame(root,background='red')
frame.pack()
canvas = Canvas(height=200,width=200)
canvas.pack()
def Image1():
canvas.delete("all")
image1 = PhotoImage(file = "c2.gif")
canvas.create_image(0,0,anchor='nw',image=image1)
canvas.image = image1
def Image2():
canvas.delete("all")
image1 = PhotoImage(file = "c1.gif")
canvas.create_image(0,0,anchor='nw',image=image1)
canvas.image = image1
TextWindow = Label(frame,anchor = NW, justify = LEFT, bg= 'white', fg = 'blue', textvariable = prompt, width = 75, height=20)
TextWindow.pack(side = TOP)
conversationbutton = Button(frame, text='right button',width=25,fg="green",command = Image1)
conversationbutton.pack(side = RIGHT)
stopbutton = Button(frame, text='left button',width=25,fg="red",command = Image2)
stopbutton.pack(side = RIGHT)
root.mainloop()
【问题讨论】:
-
这个缩进真的是你的代码的样子吗?您在无限循环
while True中有一个无限循环root.mainloop()。虽然我不知道这是否是唯一的问题,但您应该在 tkinter 程序中只调用一次mainloop。 -
原计划是只有一个“while true”的无限循环,但对于“mainloop”根本不起作用,我至少能够获得窗口。
-
一旦
root.mainloop()被调用,你必须使用回调来运行代码
标签: python python-2.7 tkinter tkinter-canvas