python 2.7 while loop, ttk.progressbar not working - python-2.7

I am working on a progress bar that keeps track of a certain function in pygame.
The following code causes a loop that I must force quit. And I can not figure our my error. Any help would be great.
from Tkinter import *
import ttk
import sys
import pygame
myGui = Tk()
myGui.title("Progress Bar")
myGui.geometry("400x200+200+300")
value_progress = StringVar()
pygame.mixer.init()
pygame.mixer.music.load("/home/david/Documents/aaa.mp3")
pygame.mixer.music.play()
def position():
global value_progress
while pygame.mixer.music.get_busy() == True:
value_progress.set(float(pygame.mixer.music.get_pos()))
b = Button(myGui, text="Start", )
b.pack()
p = ttk.Progressbar(myGui, variable=value_progress,
mode='determinate', length=350,
maximum= 512920)
p.pack()
I call the function from the shell. and then it stalls and does not come out of it.
This is only the progress bar portion of my work. However, it causes the program to crash every time.

Do not loop. Instead try following code:
def position():
global value_progress
if pygame.mixer.music.get_busy():
value_progress.set(float(pygame.mixer.music.get_pos()))
myGui.after(100, position)
Tk.after(ms, f) call f after specified ms millisecond.

Related

Python 2.7 pyperclip loop

this is the current code:
import time
import sys
import os
sys.path.append(os.path.abspath("SO_site-packages"))
import pyperclip
recent_value = ""
while True:
tmp_value = pyperclip.paste()
if not tmp_value = recent_value:
recent_value = tmp_value
print("Value changed: %s" % str(recent_value)[:20])
time.sleep(0.1)
What I'm trying to do: create a constant loop that waits for a user to copy text to clipboard, and print it whenever that happens.
What happens currently: It only prints out the last copied item and stops.
My question is: How to make this code a listening loop?
Help will be deeply appreciated.

pygame program exits with no error message when run with pythonw

I'm trying to run a pygame program using pythonw to avoid having the console window show up. This causes a weird issue related to print statements.
Basically, the program will just exit after a few seconds with no error message. The more printing I do, the faster it happens.
If I run it in idle or at the command prompt (or in linux) the program works fine. This problem only happens when launched with pythonw (right-click, Open With, pythonw).
I'm using python 2.7.11 on Windows XP 32-bit. pygame 1.9.1release.
Is there a workaround for this? Why does the program simply terminate with no error?
import pygame
from pygame.locals import *
succeeded, failed = pygame.init()
display_surface = pygame.display.set_mode((320, 240))
clock = pygame.time.Clock()
terminate = False
while terminate is False:
for event in pygame.event.get():
if event.type == QUIT:
terminate = True
area = display_surface.fill((0,100,0))
pygame.display.flip()
elapsed = clock.tick(20)
print str(elapsed)*20
pygame.quit()
You don't need to remove print statements. Save them for later debugging. ;-)
Two steps to solve this problem:
Firstly, keep all the code in py file - don't change it to pyw now; Say it is actualCode.py
Then, create a new file runAs.pyw with the following lines in it
# In runAs.pyw file, we will first send stdout to StringIO so that it is not printed
import sys # access to stdout
import StringIO # StringIO implements a file like class without the need of disc
sys.stdout = StringIO.StringIO() # sends stdout to StringIO (not printed anymore)
import actualCode # or whatever the name of your file is, see further details below
Note that, just importing actualCode runs the file, so, in actualCode.py you should not enclose the code which is executed, in what I call is it main running file condition. For example,
# In actualCode.py file
....
....
....
if __name__ == '__main__': # Don't use this condition; it evaluates to false when imported
... # These lines won't be executed when this file is imported,
... # So, keep these lines outside
# Note: The file in your question, as it is, is fine

PyQt4 and Qwt Error when opening

i´m trying to do a simple plot, using PyQt4 and Qwt5. When i start the app, it shows as i expected, but i can´t do anything, such as click or zoom for example. And if i minimize it, the plot disappears.
This is my code:
import sys
from PyQt4 import Qt
import numpy as np
import PyQt4.Qwt5.iqt
from PyQt4.Qwt5.qplt
class SimpleData(QwtPlot):
def __init__(self):
QwtPlot.__init__(self)
x = np.arange(-2*np.pi, 2*np.pi, 0.01)
p = IPlot(Curve(x, np.cos(x), Pen(Magenta,2), "cos(x)"),
Curve(x, np.exp(x), Pen(Red), "exp(x)", Y2),
Axis(Right, Log),"Ejemplo de PyQt con PyQwt")
x = x[0: -1: 10]
p.plot(Curve(x, np.cos(x-np.pi/4), Symbol(Circle, Yellow), "circle"),
Curve(x, np.cos(x+np.pi/4), Pen(Blue), Symbol(Square, Cyan), "Square"))
app = QApplication(sys.argv)
app.exec_()
The indentation is correct, maybe i made a mistake writting it here, but it´s ok.
Another thing, when i close the app, i get this error:
QObject::killTimers: timers cannot be stopped from another thread
[Finished in 2.6s with exit code -1073741510]
Thank you for your time and answers. I hope you can help me.

Rapid Gui with Qt and Python Chaper4 Alert.pyw Not Popping

i'm starting to learn Qt and i'm currently doing the alert.pyw example. The example works just fine but i wanted to test it if it really works like it's described so when i pass the time parameter i acctually put in a time to be reached (for example, now it's 11:34 and i passed 11:35 or 11:36, just to be sure i tried a few times with longer waiting times and i actually waited after time it should have popped up for a few minutes).
Well, when the set time is reachead no window actually pop up to "Wake me up".
Is this because the code actually isn't meant to work or there is something weird going on?
Here is the code:
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from future_builtins import *
import sys
import time
from PyQt4.QtCore import (QTime, QTimer, Qt, SIGNAL)
from PyQt4.QtGui import (QApplication, QLabel)
app = QApplication(sys.argv)
try:
due = QTime.currentTime()
message = "Alert!"
if len(sys.argv) < 2:
raise ValueError
hours, mins = sys.argv[1].split(":")
due = QTime(int(hours), int(mins))
if not due.isValid():
raise ValueError
if len(sys.argv) > 2:
message = " ".join(sys.argv[2:])
except ValueError:
message = "Usage: alert.pyw HH:MM [optional message]" # 24hr clock
while QTime.currentTime() < due:
time.sleep(20) # 20 seconds
label = QLabel("<font color=red size=72><b>{0}</b></font>"
.format(message))
label.setWindowFlags(Qt.SplashScreen)
label.show()
QTimer.singleShot(60000, app.quit) # 1 minute
app.exec_()
Thanks for any help

Python - Matplotlib responsive window without blocking

I have a main thread which collects data in real time. When it receives some data it adds the data to a stack. The stack is then processed by another thread which writes the data to disk.
Now i also want this thread to plot some of the data (every minute or so). I really like Matplotlibs 3D scatter plot (you can rotate and zoom with the mouse etc.). Problem is, either the window is blocking, so my program doesn't continue, or, if I make it non-blocking, the window controls are unresponsive (no mouse rotation etc.). Is there a way I can have both? I tried doing the Matplotlib stuff in another thread, but then it complains it needs to be in the main thread (tried this with default QT4 and TkAgg backend).
File: plotter.py
import numpy as np
from pylab import *
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import threading
class plotter:
def showThread(self):
plt.show()
def __init__(self):
print "plotter initializing"
# plt.ion()
fig = plt.figure()
ax1 = Axes3D(fig)
self.ax1 = ax1
ax1.scatter([0],[0],[0])
ax1.set_xlim3d(0,512,30)
ax1.set_ylim3d(0,256,30)
ax1.set_zlim3d(0,20,5)
plt.draw()
t = threading.Thread(target=self.showThread)
t.start()
def plot(self,xlist,ylist,zlist):
#This function updates the plot..
self.ax1.scatter(xlist,ylist,zlist)
self.ax1.set_xlim3d(0,512,30)
self.ax1.set_ylim3d(0,256,30)
self.ax1.set_zlim3d(0,20,5)
plt.draw()
Error TkInter:
TclError: out of stack space (infinite loop?)
Error QT4 (gives more errors):
File "/usr/lib64/python2.6/site-packages/matplotlib/backends/backend_qt4.py", line 73, in mainloop
signal.signal(signal.SIGINT, signal.SIG_DFL)
ValueError: signal only works in main thread