Prof101 Prof101 - 1 month ago 23
Python Question

Python: Tkinter pausing a while loop

So i'm trying to create a program that displays the cpu usage of your computer in real time. I wanted to use tkinter to add some buttons to the program. I decided to add a stop button that closes the program and a pause button that stops the cpu usage from updating. I was able to create the stop button but when I started the pause button I realized that I was unable to pause the while loop I using. Does anyone know what i'm doing wrong?

from tkinter import *
import psutil
from time import sleep

root = Tk()
var = StringVar()

label = Label( root, textvariable=var, relief=GROOVE, height=3, width=6, bd=4)
f = Frame(root, height=100, width=180)
f.pack_propagate(0)
f.pack()
stop=0
def pause1():
stop=1
print('It works')
def findcpu():
if stop==0:
root.update()
sleep(0.001)
cpu = psutil.cpu_percent(interval=1, percpu=False)
var.set(cpu)
label.pack()
root.update()
elif stop==1:
print('It really works')
loop=1

class pauseButton(Button):
def __init__(self, parent):
Button.__init__(self, parent)
self['text']= 'pause'
self['bg']='orange'
self['height']=3
self['width']=6
self['bd']=4
self['relief']=GROOVE
self.button=Button(self)
self['command']=pause1
self.pack(side=LEFT)
class quitButton(Button):
def __init__(self, parent):
Button.__init__(self, parent)
self['text'] = 'End'
self['bg']='red'
self['height']=3
self['width']=6
self['bd']=4
self['padx']=0
self['pady']=0
self['relief']=GROOVE
self['activebackground']='brown'
self.button = Button(self)
self['command'] = parent.destroy
self.pack(side=RIGHT)
quitButton(root)
pauseButton(root)
loop=0
stop=0
num1=0
num2=1

while loop==0:
findcpu()


root.mainloop()
print('Done')

Answer

You are using variable stop and loop as global but you are modifying it as local variable, thus global copy keep u change as initialize value. Just need to declare variable loop and stop as global to indicate you wanna access the global copy

Add line below to both pause1 and findcpu function

global stop, loop
Comments