所以我有一些值通过 RF 收发器 (NRF24L01) 从 Arduino 传到我的 Raspberry Pi,我可以在程序运行时显示整数 (Python)。现在我想在我用单独的 python 脚本编写的 GUI 中显示那些整数值。我很难这样做。我试过从 GUI 导入它们,但它不起作用,我不知道为什么..
所以现在我已经选择了将值写入传输脚本中的文本文件,然后尝试从 GUI 脚本中的文本文件中读取值,但它仍然无法正常工作。
谁能帮我更新传输脚本中的文本文件并从 GUI 脚本中读取它?能否同时从一个脚本写入文本文件并从另一个脚本读取文本文件?
任何帮助将不胜感激。谢谢!
附言。如果我遗漏了任何您需要知道的信息,请直接提问。解释一切有点困难!
GUI 代码
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 6 20:05:30 2016
@author: s
"""
import sys
if sys.version_info[0] < 3:
import Tkinter as tk
else:
import tkinter as tk
def clear():
pass
def exit_():
root.quit()
root.withdraw()
#water_amount = 0
water_cost = 0
total_water_amount = 0
total_water_cost = 0
def show_data():
while True:
text_file = open("Output.txt", "r")
water_amount = text_file.readlines()
text_file.close()
tk.Label(root, text='Water Amount: ' + str(water_amount)).pack()
tk.Label(root, text='Water Cost: ' + str(water_cost)).pack()
separator = tk.Frame(height=2, bd=10, relief=tk.SUNKEN)
separator.pack(fill=tk.X, padx=5, pady=5)
tk.Label(root, text='Total Water Amount: ' + str(total_water_amount)).pack()
tk.Label(root, text='Total Water Cost: ' + str(total_water_cost)).pack()
separator = tk.Frame(height=2, bd=10, relief=tk.SUNKEN)
separator.pack(fill=tk.X, padx=5, pady=5)
#show_data()
def get_rate():
import random
for i in range(100):
flow_rate.append(random.randint(20, 60))
# print(flow_rate)
# def draw_plot(flow_rate):
# import matplotlib.pyplot as plt
# conda install matplotlib
# print(flow_rate)
# plt.plot(flow_rate, label='Flow rate ml/sec')
# plt.xlabel('Time(sec)')
# plt.ylabel('Flow Rate(ml)')
# plt.title("Flow Rate Chart")
#
# plt.legend()
# plt.show()
root = tk.Tk(className='Water')
flow_rate = []
get_rate()
show_data()
tk.Button(root, text='Clear', command=clear).pack(side='left')
tk.Button(root, text='Exit', command=exit_).pack(side='left')
#tk.Button(root, text='Draw', command=draw_plot(flow_rate)).pack_forget()
root.mainloop()
代码接收值
import RPi.GPIO as GPIO
from lib_nrf24 import NRF24
import time
import spidev
GPIO.setmode(GPIO.BCM)
pipes = [[0xE8, 0xE8, 0xF0, 0xF0, 0xE1], [0xF0, 0xF0, 0xF0, 0xF0, 0xE1]]
radio = NRF24(GPIO, spidev.SpiDev())
radio.begin(0,17)
radio.setPayloadSize(32) #can have maximum 32
radio.setChannel(0x76)
radio.setDataRate(NRF24.BR_1MBPS) #Slower since it is secure
radio.setPALevel(NRF24.PA_MIN) # Minimum to save battery
radio.setAutoAck(True)
radio.enableDynamicPayloads()
radio.enableAckPayload() #Acknowledgement Payload : Can verify if data received
radio.openReadingPipe(1, pipes[1])
radio.printDetails()
radio.startListening()
while True:
# Waits to recieve data, if no data is recieved then goes into sleep mode
while not radio.available(0):
time.sleep(1/100)
receivedMessage = []
#Populates the message
radio.read(receivedMessage, radio.getDynamicPayloadSize())
#-------------------------------------------------------
raw = int(receivedMessage[1]) * 256
total = raw + int(receivedMessage[0])
print ("total equals:" + str(int(total)))
text_file = open("Output.txt", "w")
text_file.write("%s" % total)
text_file.close()
请您参考如下方法:
你应该尝试将数据接收代码和数据显示代码与threading库结合起来。
在数据接收脚本的 while True 循环中,它应该检查新结果并以某种方式通知 GUI 线程(例如,将其存储在全局变量中并使用 threading .Condition 对象),或者直接更改 GUI。
例如:
from tkinter import *
import threading
tk=Tk()
result=StringVar()
Label(tk,textvariable=result).pack()
def update_result():
import RPi.GPIO as GPIO
from lib_nrf24 import NRF24
import time
import spidev
GPIO.setmode(GPIO.BCM)
pipes = [[0xE8, 0xE8, 0xF0, 0xF0, 0xE1], [0xF0, 0xF0, 0xF0, 0xF0, 0xE1]]
radio = NRF24(GPIO, spidev.SpiDev())
radio.begin(0,17)
radio.setPayloadSize(32) #can have maximum 32
radio.setChannel(0x76)
radio.setDataRate(NRF24.BR_1MBPS) #Slower since it is secure
radio.setPALevel(NRF24.PA_MIN) # Minimum to save battery
radio.setAutoAck(True)
radio.enableDynamicPayloads()
radio.enableAckPayload() #Acknowledgement Payload : Can verify if data received
radio.openReadingPipe(1, pipes[1])
radio.printDetails()
radio.startListening()
while True:
while not radio.available(0):
time.sleep(1/100)
receivedMessage = []
#Populates the message
radio.read(receivedMessage, radio.getDynamicPayloadSize())
#-------------------------------------------------------
raw = int(receivedMessage[1]) * 256
total = raw + int(receivedMessage[0])
result.set(total)
threading.Thread(target=update_result).start()
mainloop()
(我没有测试这个程序,因为我没有环境,但我认为应该可以,如果不行请评论。)
