Skip to main content
 首页 » 编程设计

Python Tkinter- GPIO Pin 功能不工作

2025年05月04日17bluestorm

我是一名初级程序员,所以我没有大量的 Python 经验。我创建了一个超声波传感器系统,它使用树莓派记录水位。我的程序在控制台中运行良好,但是我想为它制作一个 GUI 以使其使用 Tkinter 更具吸引力。我以前从未使用过 Tkinter,所以我不确定自己做错了什么。我做了一个按钮,应该开始实际读取,但是每次我运行时都会收到一个错误,告诉我我无权访问 GPIO,我应该尝试以 root 身份运行——尽管当我这样做时出现同样的错误出现。

有没有人知道我哪里出错了,或者有任何其他方法可以通过 GUI 运行它?我很感激任何帮助,因为我已经在这个问题上停留了两个多月了,非常感谢!

我收到的错误信息是这样的;

"Exception in Tkinter callback 
Traceback (most recent call last): 
     File 'user/lib/python3.2/tkinter/__init__.py', line 1426, in __call__ 
          return self.func(*args) 
     File 'home.pi.tkinterproject.py', line 40 in run_code 
          GPIO.setup(GPIO.OUT) 
RuntimeErorr: No access to /dev/mem. Try running as root!" 

这是代码:

from tkinter import * 
import time 
import datetime 
import RPi.GPIO as GPIO 
GPIO.setwarnings(False)    
 
class Window(Frame): 
def     __init__(self, master = None): 
        Frame.__init__(self, master) 
 
        self.master = master 
 
        self.init_window() 
 
def init_window(self): 
 
        self.master.title("GUI") 
 
        self.pack(fill=BOTH, expand=1) 
 
        quitButton = Button(self, text = "Quit", command = self.exit_window) 
        quitButton.place(x = 330,y = 260) 
 
        runButton = Button(self, text = "Run", command = self.run_code) 
        runButton.place(x = 0, y = 0) 
 
 
def exit_window(self): 
        exit() 
 
def run_code(self): 
        #set pins according to BCM GPIO references 
        GPIO.setmode(GPIO.BCM) 
        #set GPIO pins  
        TRIG = 23 
        ECHO = 24             
        #sets trigger to send signal, echo to recieve the signal back 
        GPIO.setup(TRIG,GPIO.OUT) 
        GPIO.setup(ECHO,GPIO.IN) 
        #sets output to low 
        GPIO.output(TRIG,False) 
        myLabell = Label(text = 'Initiating measurement').pack() 
        print ("Initiating measurement..\n") 
        #gives sensor time to settle for one second 
        time.sleep(1) 
        distance = averageReading() 
        round(distance, 2) 
        print ("Distance:", distance, "cm\n") 
        print ("Saving your measurement to file..") 
        ts = time.time() 
        timestamp = datetime.datetime.fromtimestamp(ts).strftime('     %H: %M: %S     %d-%m-%Y') 
        textFile = open("sensorReadings" , "a") 
        textFile.write(str(distance)+ "cm     recorded at: ") 
        textFile.write(str(timestamp)+ "\n") 
        textFile.close()            
        #resets pins for next time 
        GPIO.cleanup() 
 
global averageReading 
 
def averageReading(): 
        readingOne = measure() 
        time.sleep(0.1)          
 
        readingTwo = measure() 
        time.sleep(0.1) 
        readingThree = measure() 
        reading = readingOne + readingTwo + readingThree 
        reading = reading / 3 
        return reading 
 
global measure         
 
def measure(): 
        global measure 
        #sends out the pulse to the trigger 
        GPIO.output(TRIG, True) 
        #short as possible 
        time.sleep(0.00001) 
        GPIO.output(TRIG,False) 
 
        while GPIO.input(ECHO) == 0: 
                pulse_start = time.time()        
        while GPIO.input(ECHO) == 1: 
                pulse_end = time.time() 
                pulse_duration = pulse_end - pulse_start 
 
                #half the speed of sound in cm/s 
                distance = pulse_duration * 34300 
                distance = distance / 2  
                #python function that rounds measurement to two digits 
                round(distance, 2) 
                return distance 
 
myGUI = Tk() 
 
myGUI.geometry("400x300") 
app = Window(myGUI) 
 
myGUI.mainloop() 

请您参考如下方法:

第一个错误:

RuntimeErorr: No access to /dev/mem. Try running as root!" 

意思就是它所说的:您需要以 root 身份运行您的代码,以便适本地访问 GPIO 子系统。当以 root 身份运行时,您会得到一个不同的错误:

NameError: global name 'averageReading' is not defined 

这是由于您的代码中的错误而发生的。首先,您似乎同时拥有一个全局变量 和 同名函数。删除这一行:

global averageReading 

还有:

global measure 

global 语句用于创建全局变量,只有在函数 block 内使用时才有意义。

您发布的代码中存在许多格式问题(多行缺少缩进),很难判断这只是复制/粘贴问题还是您的代码实际上不正确。

请尝试修复问题中的任何格式问题,使其与您的实际代码相匹配。

此外,ECHO 和 TRIG 用于 measure 函数,但从那里看不到,因此您需要修复这个。