简体   繁体   English

Python Tkinter while 循环不停止

[英]Python Tkinter while loop not stopping

#!/usr/bin/python
#--------------------------------------

Program to use stepper motor to turn knob of space heater on and off使用步进电机打开和关闭空间加热器旋钮的程序

from Tkinter import *  
import pickle 
import sys 
import time
import RPi.GPIO as GPIO
from datetime import datetime, timedelta

#import motor state
filename="Motor_State"
fileobject=open(filename,'rb')
marker=pickle.load(fileobject)
fileobject.close()


global stepper

GPIO.setmode(GPIO.BCM)

StepPins = [17,18,27,22]

for pin in StepPins:
    GPIO.setup(pin,GPIO.OUT)
    GPIO.output(pin, False)    

time.sleep(0.5)

Seq = [[1,0,0,1],
       [1,0,0,0],
       [1,1,0,0],
       [0,1,0,0],
       [0,1,1,0],
       [0,0,1,0],
       [0,0,1,1],
       [0,0,0,1]]


StepCounter=0        
stepDir=0    
StepCount=8
user=0

#Get input from user (Currently not using, trying to set up GUI) #Get input from user (目前未使用,尝试设置GUI)

def CallInput():
    global user
    #print "StepMarker: ", (marker)
    while True:
        try:
            user=int(input("Enter steps or -999 to quit:"))
        except:
            print("Sorry, invalid response.")
            continue
        if (user==999):
                Schedule()
                continue
        if (user<0 or user>3000):
            if (user==-999):
                GPIO.cleanup()
                quit()

            print ("Cannot be less than 0 or greater than 3000.")   
            continue
        else:
            break
    return user

#Save motor state #保存电机状态

def SaveMarker(state):
    fileobject=open(filename, 'wb')
    pickle.dump(marker,fileobject)
    fileobject.close()
    print ("marker saved, Goodbye!!!")

#Schedule the turning on of the heater #定时开启加热器

def Schedule():
    import datetime
    print ("hello welcome to the Scheduler!")
    print ("")
    CallInput()
    year=2017
    month=datetime.datetime.now().strftime("%m")
    hour=input("please enter the hour: ")
    AMPM=str(raw_input("AM or PM: "))

    minute=input("please enter the minute: ")
    day=input("please enter the day: ")


    if (AMPM=="PM" or AMPM== "pm"):
        print (AMPM)
        print ("hour: ", hour)
        hour+=12
        print ("hour: ", hour)
    print (year, " ", month, " ", day, " ", hour, " ", minute)
    starttime=datetime.datetime(int(year),int(month),int(day),hour,minute)
    #if (hour<int(datetime.datetime.now().strptime("%h"))
        #oneday=datetime.timedelta(days=+1)
    while datetime.datetime.now() <starttime:
        time.sleep(1)
        print("youdidit",starttime, " ", datetime.datetime.now())
    print("youdidit",starttime, " ", datetime.datetime.now())
    RunMotor(user)

#GUI attempt #GUI 尝试

class Application(Frame):
    """ A GUI application with three buttons. """
    def __init__(self, master):
        """initialize the frame"""
        Frame.__init__(self,master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        self.instruction = Label(self, text= marker )
        self.instruction.grid(row=0, column=0, columnspan=2, sticky=W)

        self.userinput= Entry(`enter code here`self)
        self.userinput.grid(row=1, column=1, sticky=W)

        self.submit_button=Button(self, text= "Submit", command=self.reveal)
        self.submit_button.grid(row=2, column=0, sticky=W)

        self.text= Text(self, width=35, height=5, wrap=WORD)
        self.text.grid(row=3, column=0, columnspan=2, sticky=W)


    def reveal(self):
        stepper=self.userinput.get()

#code for turning of the motor #电机转动代码

        global StepCount
        global StepCounter
        global StepDir
        global marker

Help!帮助! This while loop somehow ends up infinite????????????这个while循环不知何故最终无限???????????? Noob here.菜鸟在这里。 It works outside of Tkinter.它在 Tkinter 之外工作。 I literally copied and pasted the code and it just executes forever after clicking the submit button, the motor just keeps on turning and doesn't stop.我从字面上复制并粘贴了代码,单击提交按钮后它会永远执行,电机只是继续转动并且不会停止。 It should break when stepper=marker right?当 stepper=marker 正确时它应该中断吗?

        while stepper!=marker:
                print StepCounter,
                print Seq[StepCounter], "stepper: ", (stepper), "Marker: ", (marker)
                if (stepper<marker):
                    stepDir=-1
                else:
                    stepDir=1

                for pin in range(0, 4):
                    xpin = StepPins[pin]
                    if Seq[StepCounter][pin]!=0:
                        GPIO.output(xpin, True)
                    else:
                        GPIO.output(xpin, False)
                marker+=stepDir
                StepCounter += stepDir

                # If we reach the end of the sequence
                # start again
                if (StepCounter>=StepCount):
                    StepCounter = 0
                if (StepCounter<0):
                    StepCounter = StepCount+stepDir

                # Wait before moving on
                time.sleep(.006)

                for pin in StepPins:
                    GPIO.output(pin, False)
        SaveMarker(marker)
        if content == marker:
            message = "content" + str(content)

        else:
            print "success"
            message ="marker" + str(marker) +"content" + str(content)
        self.text.insert(0.0, message)

root = Tk()
root.title("Passwords")
root.geometry("250x150")
app=Application(root)
root.mainloop()
  # Start main loop
#Old code
#while True:
#    CallInput()   
#    RunMotor(user)

import atexit
atexit.register(SaveMarker)

It looks like stepper should be converted to a numerical value, probably an int :看起来stepper应该转换为数值,可能是int

stepper=self.userinput.get()
...
while stepper!=marker:
    ...
    if (stepper<marker):
    ...
    if content == marker:
        message = "content" + str(content)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM