tkinter中if语句的变量问题

大家好,我的脚本有问题,因为当我启动它进行测试并按下 L0 按钮时,我收到以下错误消息:


例外的Tkinter回调回溯(最近通话最后一个):文件“/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tkinter/初始化的.py”,线1705,在调用 返回self.func( *args) 文件“nucleo.py”,第 33 行,在 spegni 中 value = int(previous_state.get()) UnboundLocalError:在赋值之前引用了局部变量“previous_state”


我展示了我的完整代码:


import serial


import random


import time


from tkinter import *


from tkinter import messagebox


import os


previuos_state=0


def accendi():

  if previous_state == 0:

    TimeDelay = random.randrange(10,20)

    time.sleep(TimeDelay)


    ser.write('L1'.encode())


    previous_state = 1


    USER_TIME = list(ser.read(5).decode("utf8"))


    if USER_TIME[0] == 'T':



        USER_TIME = str(USER_TIME[1])+str(USER_TIME[2])+str(USER_TIME[3])+str(USER_TIME[4])


        print(str(int(USER_TIME,16))+" ms")


    else:


        print("Errore in ricezione")

  else:

    messagebox.showwarning("Attenzione", "Spegnere led per iniziare un nuovo test")

def spegni():


  if previous_state == 1:

    TimeDelay = random.randrange(10,20)

    time.sleep(TimeDelay)


    ser.write('L0'.encode())


    previous_state = 0


    USER_TIME = list(ser.read(5).decode("utf8"))


    if USER_TIME[0] == 'T':


        USER_TIME = str(USER_TIME[1])+str(USER_TIME[2])+str(USER_TIME[3])+str(USER_TIME[4])


        print(str(int(USER_TIME,16))+" ms")



    else:


        print("Errore in ricezione")


else:

    messagebox.showwarning("Attenzione", "Accendere led per iniziare un nuovo test")



我不明白为什么我不能在函数中使用变量“previuous_state”。


婷婷同学_
浏览 285回答 2
2回答

宝慕林4294392

先前状态在其初始声明中拼写错误import serialimport randomimport timefrom tkinter import *from tkinter import messageboximport ospreviuos_state=0这会使您在函数开始时的检查失败,因为未声明变量
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python