Currently I am trying to make a game with a horse that jumps obstacles that come at it, and I am currently working on the horse animation. I can get the horse to jump up, but I am still failing on implementing "gravity" and making the horse come back to the ground after it jumps.
Here's my current code:
import pyglet
import time
# background_sound = pyglet.media.load(
# 'Documents/Leave The Night On.mp3',
# streaming=False)
class horse(pyglet.sprite.Sprite):
def __init__(self, batch):
self._img_main = pyglet.image.load("sihorseav.png")
self.img_right1 = pyglet.image.load("sihorseav.png")
self.img_right2 = pyglet.image.load("sihorseav.png")
self.anim_right = pyglet.image.Animation.from_image_sequence([self.img_right1, self.img_right2], 0.5, True)
pyglet.sprite.Sprite.__init__(self, self._img_main)
self.time = 0
def forward_movement(self, flag=True):
if keymap[pyglet.window.key.UP]:
self.horse.time = time.time()
self.horse.jump()
def jump(self):
print time.time()-self.time
self.y -= -200 +20**(time.time()-self.time+.2)
class Window(pyglet.window.Window):
def __init__(self, *args, **kwargs):
super(Window, self).__init__(*args, **kwargs)
self.batch = pyglet.graphics.Batch()
self.label = pyglet.text.Label(text="Score: 0", x=850, y=650, batch=self.batch)
image = pyglet.resource.image('sibackground.jpg')
self.background = pyglet.sprite.Sprite(image, batch=self.batch)
self.player = horse(batch = self.batch)
self.keys_held = []
def on_key_press(self, symbol, modifiers):
self.keys_held.append(symbol)
if symbol == pyglet.window.key.UP:
self.player.time=time.time()
self.player.jump()
def on_draw(self):
self.clear()
self.batch.draw()
self.player.draw()
self.label.draw()
def main():
window = Window(width=960, height=700, caption='Pyglet')
pyglet.app.run()
if __name__ == '__main__':
main()
Related
How can I get access to GUI resoures, for example labelroi after conforming the roi image pixmap in class Labella...if self.ui.labelroi.setPixmap(roi image) or Principal.labelroi.setPixmap(roi image) get an error, and I'm not really clear in classes instantiation mecanism...
Another question: how could be the mouse release event, triggered into Labella 'heared' from Principal?
GUI
In MainWindow class:
labelimage: show image
labelroi: show defined roi in image
pushButtonexp: explores dir
Main Program
import sys
sys.path.append("../cursoqt/sample_editor")
from PyQt5.QtWidgets import QApplication, QFileDialog, QMainWindow
from PyQt5.QtGui import QImage, QPixmap, QPainter, QPen, QGuiApplication
from PyQt5.QtCore import Qt
from paint_rectangle import * # GUI generated by pyqt designer
from labella import * # Qlabel promoted class
class Principal(QMainWindow):
file_name = ''
def __init__(self):
super().__init__()
self.roi = QtCore.QRect()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.ui.pushButtonexp.clicked.connect(self.openFile)
self.show()
def openFile(self):
file_name, _ = QFileDialog.getOpenFileName(self, 'Open file', '/home', "Images (*.png *.jpg)")
if file_name != '':
img_pixmap = Labella.convertPixmap(self, file_name)
self.displayImg(img_pixmap)
else:
self.ui.labelimage.deleteRect()
def displayImg(self, pixmap):
if pixmap.isNull():
self.ui.labelimage.clear()
self.ui.labelimage.deleteRect()
else:
self.ui.labelimage.deleteRect()
self.ui.labelimage.setPixmap(pixmap)
self.ui.labelimage.setCursor(Qt.CrossCursor)
if __name__=='__main__':
app = QApplication(sys.argv)
window = Principal()
window.show()
sys.exit(app.exec_())
Qlabel promoted class
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QPixmap, QImage
from PyQt5.QtWidgets import QFileDialog
from paint_rectangle import * # GUI generated by pyqt designer
from call_paint_rectangle import * # Main class
class Labella(QtWidgets.QLabel):
file_n = ''
def __init__(self, parent):
super().__init__(parent=parent)
self.drawing_flg = False
self.ini_coord = QtCore.QPoint()
self.fin_coord = QtCore.QPoint()
self.exist_img_flg = 0
self.rect_roi = QtCore.QRect()
def convertPixmap(self,fileN):
Labella.file_n = fileN
pixmapformat = QPixmap(Labella.file_n)
return pixmapformat
def verifyPixmap(self):
if self.pixmap():
self.exist_img_flg = 1
else:
self.exist_img_flg = 0
def deleteRect(self):
if self.rect_roi:
self.ini_coord = self.fin_coord = QtCore.QPoint()
self.update()
def paintEvent(self, event):
super().paintEvent(event)
qp = QtGui.QPainter(self)
qp.setPen(QtGui.QPen(QtCore.Qt.red,1,QtCore.Qt.SolidLine))
if self.ini_coord and self.fin_coord and self.exist_img_flg == 1:
self.rect_roi = QtCore.QRect(self.ini_coord, self.fin_coord)
qp.drawRect(self.rect_roi)
def mousePressEvent(self, event):
# verifyPixmap verifies if there's a pixmap in qlabel
self.verifyPixmap()
if event.button() == QtCore.Qt.LeftButton and self.exist_img_flg == 1:
self.drawing_flg = True
self.ini_coord = self.fin_coord = event.pos()
elif self.exist_img_flg == 0:
self.drawing_flg = False
def mouseMoveEvent(self, event):
if self.drawing_flg:
self.fin_coord = event.pos()
self.update()
def mouseReleaseEvent(self, event):
if self.drawing_flg:
self.drawing_flg = False
self.update()
r_img = self.createMappedROI()
self.ui.labelroi.setPixmap(r_img) # HERE OCCURS THE ERROR LABELLA HAVE NOT ATTRIBUTE UI
def createMappedROI(self):
pixmap_size_Rect = self.pixmap().rect()
contents_label_Rect = QtCore.QRectF(self.contentsRect())
width_rate = pixmap_size_Rect.width()/contents_label_Rect.width()
height_rate = pixmap_size_Rect.height()/contents_label_Rect.height()
mapped_roi = QtCore.QRect(int(self.rect_roi.x() * width_rate), int(self.rect_roi.y() * height_rate),
int(self.rect_roi.width() * width_rate), int(self.rect_roi.height() * height_rate))
self.qimage = QImage()
self.qimage.load(Labella.file_n)
crop_image = self.qimage.copy(mapped_roi)
roi_image = QPixmap.fromImage(crop_image)
return roi_image
I am trying to write applications with PyGObject. I have set the app name using GLib but it seems to be broken. There is no problem with other system programs that use Turkish characters in their titles.
import sys
import gi
gi.require_version('Gtk', '4.0')
gi.require_version('Adw', '1')
from gi.repository import Gtk, Adw, GLib
class MainWindow(Gtk.ApplicationWindow):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.set_default_size(300, 400)
self.set_title("Merhaba dünya!")
GLib.set_application_name("Merhaba Dünya!")
GLib.set_prgname('Merhaba Dünya!')
self.main_box = Gtk.Box(
orientation = Gtk.Orientation.VERTICAL
)
self.set_child(self.main_box)
self.lbl_hello = Gtk.Label(
label = "Merhaba dünya"
)
self.main_box.append(self.lbl_hello)
self.btn_hello = Gtk.Button(
label = "Bana tıkla"
)
self.btn_hello.connect(
"clicked",
self.btn_hello_clicked
)
self.main_box.append(self.btn_hello)
def btn_hello_clicked(self, button):
print("Merhaba dünya!")
class MyApp(Adw.Application):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.connect('activate', self.on_activate)
def on_activate(self, app):
self.win = MainWindow(application=app)
self.win.present()
app = MyApp(application_id="net.teteos.example")
app.run(sys.argv)
I have a GUI using wxpython. My main program has several Tabs. in one of these Tabs i added a button, when this button is clicked, a new window should pop-up where some code is happening and once the user has finished and pushes the DONE button it will return to the main program and continue with the main code. I want the user to be able to copy files from one directory to another directory using the pop-up window. Once he has all the necessary files copied, the calculation will continue.
My pop-up program runs fine stand-alone, however I don't know how I can call it from the main program... I import the test.py file in my main program but how do I initiate? I tried with test.pop_up() but then I cannot close the pop-up frame anymore but only get an error message (frame2 is not defined).This is my test.py code which I wanted to call from the main frame so it is showing up as a pop-up window.
import wx
import os
import sys
import shutil
class LeftPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
label = "Buttons"
lbl = wx.StaticText(self, label=label)
self.attach_btn = wx.Button(self, -1, "Select",size = (150,25))
self.Bind(wx.EVT_BUTTON, self.OnOpen, self.attach_btn)
self.remove_btn = wx.Button(self, -1, "Remove")
self.Bind(wx.EVT_BUTTON, self.OnRemove, self.remove_btn)
v_sizer = wx.BoxSizer(wx.VERTICAL)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(v_sizer, 0, wx.ALL, 5)
sizer.Add(lbl, 0, wx.ALL|wx.CENTER, 5)
sizer.Add(self.attach_btn,0, wx.ALL |wx.EXPAND , 3)
sizer.Add(self.remove_btn,0, wx.ALL |wx.EXPAND, 3)
self.SetSizer(sizer)
def OnOpen(self, event):
print('do something')
def OnRemove(self,event):
print('do something else')
class MainPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
hsizer = wx.BoxSizer(wx.HORIZONTAL)
v_sizer = wx.BoxSizer(wx.VERTICAL)
left_panel = LeftPanel(self)
hsizer.Add(left_panel,1,wx.EXPAND)
self.done_btn = wx.Button(self, -1, "DONE")
self.Bind(wx.EVT_BUTTON, self.OnDone, self.done_btn)
v_sizer.Add(hsizer, 1, wx.EXPAND)
v_sizer.Add(self.done_btn,0, wx.ALL |wx.CENTER, 3)
self.SetSizer(v_sizer)
def OnDone(self,event):
self.Destroy()
wx.CallAfter(frame2.Destroy)
class NewFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="Costing Selection")
panel = MainPanel(self)
self.Show()
if __name__ == "__main__":
app = wx.App(False)
frame2 = NewFrame()
frame2.SetWindowStyle(wx.STAY_ON_TOP)
app.MainLoop()
def pop_up():
app = wx.App(False)
frame2 = NewFrame()
frame2.SetWindowStyle(wx.STAY_ON_TOP)
app.MainLoop()
I am not sure about the bottom of my program. Do I need the def pop_up()? I don't know how else I can call the function...
Here is a simple example.
This is your main calling program, which calls the popup
import wx
from Test import NewFrame
class TopFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="Test")
self.panel = wx.Panel(self)
self.call_button = wx.Button(self.panel, label="Call Popup")
self.call_button.Bind(wx.EVT_BUTTON, self.popup)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.panel)
self.SetSizer(sizer)
self.Show()
def popup(self, event):
pop = NewFrame()
if __name__ == "__main__":
app = wx.App()
frame2 = TopFrame()
app.MainLoop()
and here is your popup code in Test.py:
import wx
import os
import sys
import shutil
class LeftPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
label = "Buttons"
lbl = wx.StaticText(self, label=label)
self.attach_btn = wx.Button(self, -1, "Select",size = (150,25))
self.Bind(wx.EVT_BUTTON, self.OnOpen, self.attach_btn)
self.remove_btn = wx.Button(self, -1, "Remove")
self.Bind(wx.EVT_BUTTON, self.OnRemove, self.remove_btn)
v_sizer = wx.BoxSizer(wx.VERTICAL)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(v_sizer, 0, wx.ALL, 5)
sizer.Add(lbl, 0, wx.ALL|wx.CENTER, 5)
sizer.Add(self.attach_btn,0, wx.ALL |wx.EXPAND , 3)
sizer.Add(self.remove_btn,0, wx.ALL |wx.EXPAND, 3)
self.SetSizer(sizer)
def OnOpen(self, event):
print('do something')
def OnRemove(self,event):
print('do something else')
class MainPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
hsizer = wx.BoxSizer(wx.HORIZONTAL)
v_sizer = wx.BoxSizer(wx.VERTICAL)
left_panel = LeftPanel(self)
hsizer.Add(left_panel,1,wx.EXPAND)
self.done_btn = wx.Button(self, -1, "DONE")
self.Bind(wx.EVT_BUTTON, self.OnDone, self.done_btn)
v_sizer.Add(hsizer, 1, wx.EXPAND)
v_sizer.Add(self.done_btn,0, wx.ALL |wx.CENTER, 3)
self.SetSizer(v_sizer)
def OnDone(self,event):
self.Close()
self.Parent.Destroy()
class NewFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="Costing Selection")
panel = MainPanel(self)
self.SetWindowStyle(wx.STAY_ON_TOP)
self.Show()
The only real difference is the OnDone function, which because of the way the code is written, needs to Close self and Destroy the parent. Otherwise we would destroy MainPanel but leave it's parent NewFrame in place.
i have a spinbox like:
input = QDoubleSpinBox()
input.value = 0.02
In the gui, it shows:
2.00
But i like that it shows
0.02
how should i do?
If you like that it shows 0.02
You will probably need to set the precision of the step in decimal places
for example: setSingleStep (0.02)
import sys
from PyQt5.QtWidgets import (QApplication, QMainWindow, QLabel,
QVBoxLayout, QDoubleSpinBox)
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.initWindow()
def initWindow(self):
vBoxLayout = QVBoxLayout()
self.label = QLabel("Current Value", self)
self.label.move(60, 60)
vBoxLayout.addWidget(self.label)
self.spinBox = QDoubleSpinBox(self)
self.spinBox.move(60, 30)
self.spinBox.setMinimum(0)
self.spinBox.setMaximum(12)
self.spinBox.setSingleStep(0.02)
self.spinBox.valueChanged.connect(self.valueChanged)
def valueChanged(self):
self.label.setText("Current Value {:.2f}".format(self.spinBox.value()))
if __name__ == '__main__':
aplicacion = QApplication(sys.argv)
window = Window()
window.setGeometry(100, 100, 220, 100)
window.show()
sys.exit(aplicacion.exec_())
The IPywidgets manual is very helpful for the most part, but is lacking some explanation about how one goes about creating complex dashboards. In particular, I am trying to figure our how to:
Design abstractions to assist in building easily extendable dashboards which contain multiple interdependent widgets, some of which hide/show other widgets.
Do this in a way which would allow me to get and set the state of all the widgets as a dict so I could subsequently implement buttons to save and load the configuration of my dashboard to a JSON file.
To make this question more concrete, I designed a minimal example of my current approach, which based on a design pattern I received from #jasongrout on the Jupyter Widgets channel on Gitter; when answering, please demonstrate your design pattern by reimplementing this example in it, ensuring the two criteria above are clearly fulfilled:
from IPython.display import display
import IPython.display as ipd
import ipywidgets as widgets
import matplotlib.pyplot as plt
class ModelUI:
def __init__(self):
self.par = dict()
self.initUI()
def initUI(self):
self.funcPars = widgets.VBox()
self.initLinear()
self.initQuadratic()
self.initFunc()
self.initButton()
self.initOutput()
self.controls = widgets.HBox([
self.func,
self.funcPars,
self.plot
])
self.UI = widgets.VBox([
self.controls,
self.output
])
def initFunc(self):
self.func = widgets.Dropdown(
description="Function:",
options=[
"Linear",
"Quadratic"
])
self.func.observe(self.updateFunc, "value")
self.updateFunc(None)
def initButton(self):
self.plot = widgets.Button(description="Plot")
self.plot.on_click(self.plotFunction)
def updateFunc(self, change):
if self.func.value == "Linear":
self.funcPars.children = self.linPars
self.par['func'] = "Linear"
elif self.func.value == "Quadratic":
self.funcPars.children = self.quadPars
self.par['func'] = "Quadratic"
else:
pass
def initLinear(self):
self.m = widgets.FloatSlider(
description="m",
min=-10, max=10, value=2)
self.k = widgets.FloatSlider(
description="k",
min=-10, max=10, value=1)
self.linPars = [self.m, self.k]
self.m.observe(self.updateLinear, "value")
self.k.observe(self.updateLinear, "value")
self.updateLinear(None)
def updateLinear(self, change):
self.par['m'] = self.m.value
self.par['k'] = self.k.value
def initQuadratic(self):
self.a = widgets.FloatSlider(
description="a",
min=-10, max=10, value=1)
self.b = widgets.FloatSlider(
description="b",
min=-10, max=10, value=2)
self.c = widgets.FloatSlider(
description="c",
min=-10, max=10, value=3)
self.quadPars = [self.a, self.b, self.c]
self.a.observe(self.updateQuadratic, "value")
self.b.observe(self.updateQuadratic, "value")
self.c.observe(self.updateQuadratic, "value")
self.updateQuadratic(None)
def updateQuadratic(self, change):
self.par['a'] = self.a.value
self.par['b'] = self.b.value
self.par['c'] = self.c.value
def initOutput(self):
self.output = widgets.Output()
self.plotFunction(None)
def plotFunction(self, change):
self.function = {
"Linear": lambda x: self.par['m']*x + self.par['k'],
"Quadratic": lambda x: self.par['a']*x**2 + self.par['b']*x + self.par['c']
}
with self.output:
ipd.clear_output()
xvals = [ i/10 for i in range(-100,100)]
yvals = list(map(self.function[self.par['func']], xvals))
plt.plot(xvals,yvals)
plt.show()
def _ipython_display_(self):
display(self.UI)
ModelUI()