How to handle QPropertyAnimation for a large number of widgets - python

I want to have many colored dots constantly move across a background. (Description of code below): A PolkaDot widget is constructed with a random color, size, position, and duration. The QPropertyAnimation moves the widget across the screen from left to right, restarting at a new height when the animation ends. 100 PolkaDot widgets are constructed in the Background widget, which is enough to make it appear like tons of new dots are constantly rushing in from the left side of the screen.
However, the 100 property animations seem to consume a lot of CPU power, causing it to slow down and look un-smooth. Is there another way to achieve a similar result? Try running the code below.
import sys, random
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
colors = [QColor('#f00'), QColor('#00f'), QColor('#0f0'), QColor('#ff0'),
QColor('#fff'), QColor('#ff6000'), QColor('#6b00ff'), QColor('#f0f')]
class PolkaDot(QWidget):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setFixedSize(50, 50)
self.color = random.choice(colors)
self.r = random.randrange(5, 22)
self.move(random.randrange(w), random.randrange(h))
self.anim = QPropertyAnimation(self, b'pos')
self.anim.finished.connect(self.run)
self.anim.setDuration(random.randrange(3000, 9000))
self.anim.setStartValue(QPoint(self.x() - (w + 60), self.y()))
self.anim.setEndValue(QPoint(w + 60, self.y()))
self.anim.start()
def paintEvent(self, event):
qp = QPainter(self)
qp.setRenderHint(QPainter.Antialiasing)
qp.setBrush(self.color)
qp.setPen(QPen(self.color.darker(130), self.r / 5))
qp.drawEllipse(QPoint(25, 25), self.r, self.r)
def run(self):
y = random.randrange(h)
self.anim.setDuration(random.randrange(3000, 9000))
self.anim.setStartValue(QPoint(-60, y))
self.anim.setEndValue(QPoint(w + 60, y + random.randrange(-50, 50)))
self.anim.start()
class Background(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(window)
polka_dots = [PolkaDot(self) for i in range(100)]
self.setStyleSheet('background-color: #000')
if __name__ == '__main__':
app = QApplication(sys.argv)
window = QDesktopWidget().availableGeometry()
w, h = window.width(), window.height()
gui = Background()
gui.show()
sys.exit(app.exec_())

I sort of found a solution. For some reason, creating the dots in the background widget's paint event and calling repaint() on QTimer.timeout() to update the XY coordinates is much more efficient than using QPropertyAnimation.
tick = 24
class Dot(object):
def __init__(self):
self.x = random.randrange(-w - 60, 0)
self.randomize()
def randomize(self):
self.color = random.choice(colors)
self.r = random.randrange(5, 22)
self.y = random.randrange(h)
self.x_speed = random.randrange(3000, 9000)
self.y_speed = random.randrange(-50, 50)
def move(self):
self.x += w * tick / self.x_speed
self.y += self.y_speed * tick / self.x_speed
if self.x > w:
self.x = -60
self.randomize()
class Background(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(window)
self.setStyleSheet('background-color: #000')
self.dots = [Dot() for i in range(150)]
self.timer = QTimer()
self.timer.setInterval(tick)
self.timer.timeout.connect(self.animate)
self.timer.start()
def paintEvent(self, event):
qp = QPainter(self)
qp.setRenderHint(QPainter.Antialiasing)
for dot in self.dots:
qp.setBrush(dot.color)
qp.setPen(QPen(dot.color.darker(130), dot.r / 5))
qp.drawEllipse(QPoint(dot.x, dot.y), dot.r, dot.r)
def animate(self):
for d in self.dots:
d.move()
self.repaint()

Related

tkinter: object with different movement patterns

I'm working on a simulation in which some cubes of the same class are moving randomly. My aim is to give them another moving pattern, when they fulfill some characteristics (for example their object number).
My Problem:
If they fulfill the characteristics, how can I "switch off" the first moving pattern and activate the next?
Here a strongly simplified example of the simulation, and how it doesn't work:
from tkinter import *
from random import *
class Cubes:
def __init__(self, master, canvas, number, x1, y1, color):
self.master = master
self.canvas = canvas
self.number = number
self.x1 = x1
self.y1 = y1
self.x2 = x1 + 15
self.y2 = y1 + 15
self.color = color
self.rectangle = canvas.create_rectangle(x1, y1, self.x2, self.y2, fill=color)
def movement(self):
self.x = randint(-10, 10)
self.y = randint(-10, 10)
canvas.move(self.rectangle, self.x, self.y)
if self.number == 2:
def movementII(self):
canvas.move(self.rectangle, 0, 0)
self.canvas.after(100, self.movementII)
self.canvas.after(100, self.movement)
if __name__ == "__main__":
master = Tk()
canvas = Canvas(master, width=900, height=600)
canvas.pack()
master.title("Simulation")
cube = Cubes(master, canvas, 2, randint(50, 800), randint(25, 500), "black")
cube.movement()
mainloop()
how can I "switch off" the first moving pattern and activate the next?
When you call after, it returns a unique identifier. You can save that identifier and then later pass it to after_cancel to cancel the job if it hasn't already run.
I'm not entirely clear what you want, but if you want to turn off the old movement when you switch to the new, it would look something like this:
class Cubes:
def __init__(self, master, canvas, number, x1, y1, color):
...
self.after_id = None
...
def cancel(self):
if self.after_id is not None:
self.after_cancel(self.after_id)
self.after_id = None
def movement(self):
self.x = randint(-10, 10)
self.y = randint(-10, 10)
canvas.move(self.rectangle, self.x, self.y)
if self.number == 2:
def movementII(self):
canvas.move(self.rectangle, 0, 0)
self.cancel()
self.after_id = self.canvas.after(100, self.movementII)
self.after_id = self.canvas.after(100, self.movement)
A better way might be to have a single method that you call with after, and it simply calls the appropriate method.
For example, something like this:
def move(self):
if self.number == 1:
self.movement_1()
elif self.number == 2:
self.movement_2()
self.canvas.after(100, self.move)
def movement_1(self):
self.x = randint(-10, 10)
self.y = randint(-10, 10)
canvas.move(self.rectangle, self.x, self.y)
def movement_2(self):
canvas.move(self.rectangle, 0, 0)
Then, to switch the movement method, just change self.number and it will automatically be called at the appropriate time.

Python Pyglet Using External Fonts For Labels

I'm working on a project at the moment and I have been trying to change the fonts of the labels in the pyglet library to fonts that I found online but I couldn't get it to work. I tried searching online for an hour now and nothing seems to be working. Added some code for reference:
font.add_file('ZukaDoodle.ttf')
ZukaDoodle = font.load('ZukaDoodle.ttf', 16)
PlayLabel = pyglet.text.Label('Go', font_name='ZukaDoodle', font_size=100, x=window.width // 2,
y=window.height - 450, anchor_x='center', anchor_y='center',
batch=buttons_batch,
color=(0, 0, 0, 1000), width=250, height=130)
So the error is pretty simple. The loaded font-name is not ZukaDoodle, it's Zuka Doodle with a space. Here's a working executable sample:
from pyglet import *
from pyglet.gl import *
font.add_file('ZukaDoodle.ttf')
ZukaDoodle = font.load('ZukaDoodle.ttf', 16)
key = pyglet.window.key
class main(pyglet.window.Window):
def __init__ (self, width=800, height=600, fps=False, *args, **kwargs):
super(main, self).__init__(width, height, *args, **kwargs)
self.x, self.y = 0, 0
self.keys = {}
self.mouse_x = 0
self.mouse_y = 0
self.PlayLabel = pyglet.text.Label('Go', font_name='Zuka Doodle', font_size=100,
x=self.width // 2,
y=self.height - 450,
anchor_x='center', anchor_y='center',
color=(255, 0, 0, 255),
width=250, height=130)
self.alive = 1
def on_draw(self):
self.render()
def on_close(self):
self.alive = 0
def on_mouse_motion(self, x, y, dx, dy):
self.mouse_x = x
def on_key_release(self, symbol, modifiers):
try:
del self.keys[symbol]
except:
pass
def on_key_press(self, symbol, modifiers):
if symbol == key.ESCAPE: # [ESC]
self.alive = 0
self.keys[symbol] = True
def render(self):
self.clear()
self.PlayLabel.draw()
## Add stuff you want to render here.
## Preferably in the form of a batch.
self.flip()
def run(self):
while self.alive == 1:
self.render()
# -----------> This is key <----------
# This is what replaces pyglet.app.run()
# but is required for the GUI to not freeze
#
event = self.dispatch_events()
if __name__ == '__main__':
x = main()
x.run()
The key difference here is font_name='Zuka Doodle'.
Also, the alpha channel usually doesn't need to be higher than 255 since that's the max value of a colored byte, so unless you're using 16-bit color representation per channel, 255 will be the maximum value.

Redraw circle - python

I have this bit of code here:
from tkinter import *
class player():
def __init__(self, radius, xcoordinate = 0, ycoordinate = 0):
self.xcoordinate = xcoordinate
self.ycoordinate = ycoordinate
self.radius = radius
def moveRight(self, event):
self.xcoordinate += 25
self.draw()
print("Right key pressed")
print("x: " + str(self.xcoordinate))
def moveLeft(self, event):
self.ycoordinate += 25
self.draw()
print("Left key pressed")
print("y: " + str(self.ycoordinate))
def draw(self):
world = client()
world.title("World")
world.bind('<Right>', self.moveRight)
world.bind('<Left>', self.moveLeft)
canvas = Canvas(world, width=200, height=200, borderwidth=0,highlightthickness=0, bg="black")
canvas.grid()
canvas.draw_player(self.xcoordinate, self.ycoordinate, self.radius, fill="blue", width=4)
world.mainloop()
class client(Tk):
def __init__(self):
super().__init__()
def draw_player(self, x, y, r, **kwargs):
return self.create_oval(x-r, y-r, x+r, y+r, **kwargs)
Canvas.draw_player = draw_player
p1 = player(50)
p1.draw()
The problem is that whenever I press the right or left arrow keys, it calls the draw() method. The draw() method constructs a new client object and etc.
So you end up opening multiple windows each with a circle with different x and y coordinates. How do I make this such that when I call draw() it only edits the x and y coordinates and redraws the circle on the same window?
Please no suggestions to use pygame, my IDE gets errors when I try to import the module.
The code can be simplified by passing the move parameters to a single function.
from tkinter import *
from functools import partial
class player():
def __init__(self, master, radius, xcoordinate=100, ycoordinate=100):
self.master=master
self.xcoordinate = xcoordinate
self.ycoordinate = ycoordinate
self.radius = radius
self.master.title("World")
self.master.bind('<Right>', partial(self.move_oval, 25, 0))
self.master.bind('<Left>', partial(self.move_oval, -25, 0))
self.master.bind('<Up>', partial(self.move_oval, 0, -25))
self.master.bind('<Down>', partial(self.move_oval, 0, 25))
self.draw() ## called once
def move_oval(self, x, y, event):
self.canvas.move(self.oval_id, x, y)
print("key pressed", x, y)
def draw(self):
self.canvas = Canvas(self.master, width=200, height=200,
borderwidth=0,highlightthickness=0, bg="black")
self.canvas.grid()
self.oval_id=self.canvas.create_oval(self.xcoordinate-self.radius,
self.ycoordinate-self.radius,
self.xcoordinate+self.radius,
self.ycoordinate+self.radius,
fill="red")
master=Tk()
p1 = player(master, 50)
master.mainloop()
I assume that
redraws the circle on the same window
means moving the circle, and does not mean drawing a second circle in the same space. Use the move() function for a canvas object to do this http://effbot.org/tkinterbook/canvas.htm . Note that you have to save a reference to the object to be moved. Also your moveLeft() function doesn't.
class Player():
def __init__(self, master, radius, xcoordinate=100, ycoordinate=100):
self.master=master
self.xcoordinate = xcoordinate
self.ycoordinate = ycoordinate
self.radius = radius
self.master.title("World")
self.master.bind('<Right>', self.moveRight)
self.master.bind('<Left>', self.moveLeft)
self.draw() ## called once
def moveRight(self, event):
self.canvas.move(self.oval_id, 25, 0)
print("Right key pressed")
print("x: " + str(self.xcoordinate))
def moveLeft(self, event):
self.canvas.move(self.oval_id, 0, 25)
print("Left key pressed")
print("y: " + str(self.ycoordinate))
def draw(self):
self.canvas = Canvas(self.master, width=200, height=200,
borderwidth=0,highlightthickness=0, bg="black")
self.canvas.grid()
self.oval_id=self.canvas.create_oval(self.xcoordinate-self.radius,
self.ycoordinate-self.radius,
self.xcoordinate+self.radius,
self.ycoordinate+self.radius,
fill="red")
master=Tk()
p1 = Player(master, 50)
master.mainloop()

How to stop other processes or finish processes in Python / Tkinter program

I have been drawing some graphics with a Python / Tkinter program. The program has a main menu with menu items for drawing different figures. It works quite well but I came up against a problem. If the program is part way through drawing one figure and the user clicks to draw a second figure then the program draws the second figure, but when it has finished drawing the second figure it goes back and finishes drawing the first figure. What I want it to do is stop drawing the first figure and not go back to drawing the first figure even when the second figure has finished drawing. I created an simpler example program to demonstrate the scenario. To see the problem in this program click "Draw -> Red" and then click "Draw -> Blue" before the red has finished drawing. How do I get the program to abort any previous drawing? Here is the example program:
from tkinter import *
import random
import math
def line(canvas, w, h, p, i):
x0 = random.randrange(0, w)
y0 = random.randrange(0, h)
x1 = random.randrange(0, w)
y1 = random.randrange(0, h)
canvas.create_line(x0, y0, x1, y1, fill=p.col(i))
class Color:
def __init__(self, r, g, b):
self.red = r
self.gre = g
self.blu = b
def hexVal(self, v):
return (hex(v)[2:]).zfill(2)
def str(self):
return "#" + self.hexVal(self.red) + self.hexVal(self.gre) + self.hexVal(self.blu)
class Palette:
def __init__(self, n0, y):
self.colors = []
self.n = n0
self.m = 0
if y == "red":
self.red()
elif y == "blue":
self.blue()
def add(self, c):
self.colors.append(c)
self.m += 1
def red(self):
self.add(Color(127, 0, 0))
self.add(Color(255, 127, 0))
def blue(self):
self.add(Color(0, 0, 127))
self.add(Color(0, 127, 255))
def col(self, i):
k = i % (self.n*self.m)
z = k // self.n
j = k % self.n
c0 = self.colors[z]
c1 = self.colors[(z + 1) % self.m]
t0 = (self.n - j)/self.n
t1 = j/self.n
r = int(math.floor(c0.red*t0 + c1.red*t1))
g = int(math.floor(c0.gre*t0 + c1.gre*t1))
b = int(math.floor(c0.blu*t0 + c1.blu*t1))
c = Color(r, g, b)
return c.str()
def upd(canvas):
try:
canvas.update()
return True
except TclError:
return False
def tryLine(canvas, w, h, p, i, d):
try:
line(canvas, w, h, p, i)
if i % d == 0:
upd(canvas)
return True
except TclError:
return False
class MenuFrame(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
self.WIDTH = 800
self.HEIGHT = 800
self.canvas = Canvas(self.parent, width=self.WIDTH, height=self.HEIGHT)
self.pack(side=BOTTOM)
self.canvas.pack(side=TOP, fill=BOTH, expand=1)
self.parent.title("Line Test")
menubar = Menu(self.parent)
self.parent.config(menu=menubar)
self.parent.protocol('WM_DELETE_WINDOW', self.onExit)
menu = Menu(menubar)
menu.add_command(label="Red", command=self.onRed)
menu.add_command(label="Blue", command=self.onBlue)
menu.add_command(label="Exit", command=self.onExit)
menubar.add_cascade(label="Draw", menu=menu)
self.pRed = Palette(256, "red")
self.pBlue = Palette(256, "blue")
def onRed(self):
# How to abort here any processes currently running?
self.canvas.delete("all")
for i in range(0, 7000):
tryLine(self.canvas, self.WIDTH, self.HEIGHT, self.pRed, i, 100)
upd(self.canvas)
def onBlue(self):
# How to abort here any processes currently running?
self.canvas.delete("all")
for i in range(0, 7000):
tryLine(self.canvas, self.WIDTH, self.HEIGHT, self.pBlue, i, 100)
upd(self.canvas)
def onExit(self):
self.canvas.delete("all")
self.parent.destroy()
def main():
root = Tk()
frame = MenuFrame(root)
root.mainloop()
if __name__ == '__main__':
main()
That's the simple example? ;)
You can add a variable that tracks the currently selected method, then check if that variable exists before completing the for loop. Here's an even simpler example:
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
Button(self, text='Task A', command=self._a).pack()
Button(self, text='Task B', command=self._b).pack()
self.current_task = None # this var will hold the current task (red, blue, etc)
def _a(self):
self.current_task = 'a' # set the current task
for i in range(1000):
if self.current_task == 'a': # only continue this loop if its the current task
print('a')
self.update()
def _b(self):
self.current_task = 'b'
for i in range(1000):
if self.current_task == 'b':
print('b')
self.update()
root = Tk()
Example(root).pack()
root.mainloop()
Let me know if that doesn't make sense or doesn't work out for you.

The item configure method didn't work in Tkinter

I tried to use the Tkinter library for my small project in python. I create a 500 by 500 square with 10000 small square in it.
And I want each small square turns black when user click on it. Can someone please tell me why, I would really appreciate it. Here is the graphics code:
from Tkinter import *
from button import *
class AppFrame(Frame):
def __init__(self):
self.root = Tk()
self.root.geometry = ("1000x1000")
self.f = Frame(self.root, relief = 'sunken', width = 600, height = 600)
self.w = Canvas(self.f,width = 505, height =505)
##get the x, y value whenever the user make a mouse click
self.w.bind("<Button-1>", self.xy)
self.bolist = []
for k in range(1,101):
for i in range(1, 101):
button = Buttons(self.w, i * 5, k * 5, i * 5 + 5, k * 5 + 5)
self.bolist.append(button)
self.f.grid(column =0, columnspan = 4)
self.w.grid(column = 0)
self.root.mainloop()
def xy (self, event):
self.x, self.y = event.x, event.y
print (self.x, self.y)
##check each button if it's clicked
for hb in self.bolist:
if hb.clicked(self.x, self.y):
print ("hurry")
hb.activate()
And
##button.py
from Tkinter import *
class Buttons:
def __init__(self,canvas,bx,by,tx,ty):
self.canvas = canvas
self.rec = canvas.create_rectangle((bx,by,tx,ty),fill = "lightgray",
activefill= 'black', outline = 'lightgray')
self.xmin = bx
self.xmax = tx
self.ymin = by
self.ymax = ty
##print (bx, by, tx, ty)
def clicked(self, px, py):
return (self.active and self.xmin <= px <= self.xmax and
self.ymin <= py <= self.ymax)
def activate(self):
self.canvas.itemconfigure(slef.rec, fill = 'black')
self.active = True
The problem is that you don't initialize the active attribute, so it doesn't exist until the cell becomes active. To fix that, add self.active = False inside the __init__ method of Buttons.
You also have a typo in this line (notice you use slef rather than self):
self.canvas.itemconfigure(slef.rec, fill = 'black')
Instead of a global binding on the canvas, it would be more efficient to set a binding on each individual rectangle. You can then use the binding to pass the instance of the Buttons class to the callback. This way you don't have to iterate over several thousand widgets looking for the one that was clicked on.
To do this, use the tag_bind method of the canvas. You can make it so that your main program passes in a reference to a function to call when the rectangle is clicked, then the binding can call that method and pass it a reference to itself.
For example:
class Buttons:
def __init__(self,canvas,bx,by,tx,ty, callback):
...
self.rec = canvas.create_rectangle(...)
self.canvas.tag_bind(self.rec, "<1>",
lambda event: callback(self))
...
class AppFrame(Frame):
def __init__(...):
...
button = Buttons(..., self.callback)
...
def callback(self, b):
b.activate()
Here, I looked at your code, debugged it, and made some adjustments. It works now.
Just keep both the scripts in one folder and run your AppFrame script (the second one in this answer)
##button.py
from Tkinter import *
class Buttons:
def __init__(self,canvas,bx,by,tx,ty):
self.canvas = canvas
self.rec = canvas.create_rectangle((bx,by,tx,ty),fill = "lightgray", activefill= 'black', outline = 'lightgray')
self.xmin = bx
self.xmax = tx
self.ymin = by
self.ymax = ty
##print (bx, by, tx, ty)
def clicked(self, px, py):
return (self.xmin <= px <= self.xmax and
self.ymin <= py <= self.ymax)
def activate(self):
self.canvas.itemconfigure(self.rec, fill = 'black')
AND
from Tkinter import *
from button import *
class AppFrame(Frame):
def __init__(self):
self.root = Tk()
self.root.geometry = ("1000x1000")
self.f = Frame(self.root, relief = 'sunken', width = 600, height = 600)
self.w = Canvas(self.f,width = 505, height =505)
##get the x, y value whenever the user make a mouse click
self.w.bind("<Button-1>", self.xy)
self.bolist = []
for k in range(1,101):
for i in range(1, 101):
button = Buttons(self.w, i * 5, k * 5, i * 5 + 5, k * 5 + 5)
self.bolist.append(button)
self.f.grid(column =0, columnspan = 4)
self.w.grid(column = 0)
self.root.mainloop()
def xy (self, event):
self.x, self.y = event.x, event.y
print (self.x, self.y)
##check each button if it's clicked
for hb in self.bolist:
if hb.clicked(self.x, self.y):
print ("hurry")
hb.activate()
newApp = AppFrame()

Categories