Python Forum
migrate code from tkinter to pygame
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
migrate code from tkinter to pygame
#1
Hi,

I already post about this but i am totally lost i have no clue how to make it work. I am unable to make my button work in tkinter. So i have to make it work in pygame or pyside so my button may work.
this is a new approach but i cant chose between the 2 albums. The album will switch only if i click button first before starting the script.

from PySide.QtCore import *
from PySide.QtGui import *
import RPi.GPIO as GPIO
from time import sleep
import datetime
import time
import yaml
fichier = open("output.yaml", "r")
fichier1 = open("output1.yaml", "r")
document = yaml.load(fichier, Loader=yaml.Loader)
documents = yaml.load(fichier1, Loader=yaml.Loader)
print(documents["heure"])
print(document["heure"])

GPIO.setmode(GPIO.BOARD)
button1=16
button2=12
GPIO.setup(button1,GPIO.IN,pull_up_down=GPIO.PUD_UP)
GPIO.setup(button2,GPIO.IN,pull_up_down=GPIO.PUD_UP)
dateSTR = datetime.datetime.now().strftime("%H:%M:%S" )

class Slides(QWidget):
    def __init__(self, image_files, parent=None):
        QWidget.__init__(self, parent)
        self.image_files = image_files
        print(datetime.datetime.now())
        if dateSTR > ("08:30:00") and dateSTR < (document["heure"]):  <--------how can we pass the hour from a file to stop the program?
 
            s = '<>'*300
            self.label = QLabel(s, self)
            self.label.setGeometry(10, 30, 1200, 800)

            self.button = QPushButton("D�but du diaporama",self)
            self.button.setGeometry(10, 10, 160, 30)
            self.button.clicked.connect(self.timerEvent)

            self.timer = QBasicTimer()
            self.step = 0
            if GPIO.input(button2)==0:                               <--------------i would like to freeze image when i click the button instead of freezing the whole script
                self.delay = 20000  # milliseconds
            if GPIO.input(button2)==1:
                self.delay = 2000 
            sf = "Slides are shown {} seconds apart"
            self.setWindowTitle(sf.format(self.delay/1000.0))

    def timerEvent(self, e=None):
        if self.step >= len(self.image_files):
            self.timer.stop()
            self.button.setText('Fin du diaporama')
            return
        self.timer.start(self.delay, self)
        file = self.image_files[self.step]
        image = QPixmap(file)
        self.label.setPixmap(image)
        self.setWindowTitle("{} --> {}".format(str(self.step), file))
        self.step += 1


# pick image files you have in the working folder
# or give full path name
if GPIO.input(button1)==1:
        #if func1==False:    
            #func1=True
            #sleep(.1)
 image_files = [
    '/home/pi/Desktop/jpg2png/athenaR.png',
'/home/pi/Desktop/jpg2png/EosR.png',
'/home/pi/Desktop/jpg2png/k.png',
'/home/pi/Desktop/jpg2png1/athena1.png',
'/home/pi/Desktop/jpg2png1/meteor.png',
'/home/pi/Desktop/jpg2png/falconR.png',
'/home/pi/Desktop/jpg2png/seacloudR.png',
'/home/pi/Desktop/jpg2png/SeagleR.png'
]
  
         
if GPIO.input(button1)==0:
        #if func2==False:    

           # func2=True
  image_files1 = [
    '/home/pi/Desktop/jpg2png2/Ar.png',
'/home/pi/Desktop/jpg2png2/AntibeR.png',
'/home/pi/Desktop/jpg2png2/dubai.png',
'/home/pi/Desktop/jpg2png2/KHALILAHR.png',
'/home/pi/Desktop/jpg2png2/luxuy-yachtR.png',
'/home/pi/Desktop/jpg2png2/turquoiseR.png',
]





app = QApplication([])
if GPIO.input(button1)==1:
    w = Slides(image_files)
if GPIO.input(button1)==0:
    w = Slides(image_files1)
# setGeometry(x, y, w, h)  x,y = upper left corner coordinates
w.setGeometry(100, 100, 1200, 800)
w.show()
app.exec_()
I have no clue how to solve the problem.

Thank you
Reply
#2
You will get no benefit going from tkinter to Qt (PySide). In both cases your difficulties are caused by the blocking event loop (mainloop() in tkinter, exec() in Qt). And in both cases there are ways to schedule events that can be used to periodically run a function. In tkinter this is done using .after(). In Qt there are multiple ways to accomplish this, but the easiest to understand is probably QTimer.
Reply
#3
The teacher said i should stick to pygame cause its easier to make button works. Frankly i end up with the same issue with Tkinter, Pygame or PySide. Button works only if press before compiling. I tried flag, than import the function from another file. That's funny cause the teacher made her example work by pressing button before compiling. Good thing she is not cheap when it's time to give points. I don't have much time for this assignment i will research this QTimer option.
Thank you
Reply
#4
I recommend against trying to use qt. There is no magic bullet there that will make this task any easier. Stick with tkinter or pygame and work on your program design. Start with something really simple. Start with printing "Button 1" when GPIO.input(button1) is pressed. Work on that program until it only prints "Button 1" one time for each press/release (holding the button a long time should be exactly the same as a quick click).
Reply
#5
Hello,

I am trying to separate in different files my class, and my init and timerEvent method.
Import the class in the main file and import the methods from 3 differents files.

Do i have to include arguments in my methods as well? Example:

If the name of my file is init i will import __init__() from init file.
do i have to include __init__(self, ligne, parent=None)?


How do you import class and methods?

Thank you

 """

Projet 3 Cadre num�rique � haute r�solution
"""
from PySide.QtCore import *
from PySide.QtGui import *
import RPi.GPIO as GPIO
from time import sleep
import datetime
import time
import yaml
#fichier yaml configuration de l'intervalle
fichier = open("diaporama.yaml", "r")
document = yaml.load(fichier, Loader=yaml.Loader)
print(document["heureA"])
print(document["heureD"])
#fichier yaml configuration du choix d'images
with open('voilier.yaml') as y:
    for ligne in y:
        print(ligne)
with open('yatch.yaml') as yatch:
    for y in yatch:
        print(y)
#connection Raspberry Pi
GPIO.setmode(GPIO.BOARD)
GPIO.setup(document["bouton1"],GPIO.IN,pull_up_down=GPIO.PUD_UP)
GPIO.setup(document["bouton2"],GPIO.IN,pull_up_down=GPIO.PUD_UP)
dateSTR = datetime.datetime.now().strftime("%H:%M:%S" )

class Diapo(QWidget):
    def __init__(self, ligne, parent=None):
            QWidget.__init__(self, parent)
            self.ligne = ligne
            s = '<>'*300
            self.label = QLabel(s, self)
            self.label.setGeometry(10, 30, 1200, 800)

            self.bouton = QPushButton("D�but du diaporama",self)
            self.bouton.setGeometry(10, 10, 160, 30)
            self.bouton.clicked.connect(self.timerEvent)
            self.timer = QBasicTimer()
            self.step = 0
            self.delay = document["secondeP"]*1000
            sf = "Yachts et voiliers de luxe"
            self.setWindowTitle(sf.format(self.delay/1000.0))

    def timerEvent(self, e=None):
        if self.step >= len(self.ligne):
            self.timer.stop()
            self.bouton.setText('Fin du diaporama')
            return
        print(datetime.datetime.now())
        if dateSTR > (document["heureA"]) and dateSTR < (document["heureD"]):
            self.timer.start(self.delay, self)
            fichier = self.ligne[self.step]
            image = QPixmap(fichier)
            self.label.setPixmap(image)
            if GPIO.input(document["bouton2"])==1:
                self.step += 1
            if GPIO.input(document["bouton2"])==0:
                self.step += 0
                self.delay = document["seconde"]*60*1000

# liste d'images

if GPIO.input(document["bouton1"])==1:
        
 image_voiliers = [
    '/home/pi/Desktop/jpg2png/athenaR.png',
'/home/pi/Desktop/jpg2png/EosR.png',
'/home/pi/Desktop/jpg2png/k.png',
'/home/pi/Desktop/jpg2png1/meteor.jpg',
'/home/pi/Desktop/jpg2png/falconR.png',
'/home/pi/Desktop/jpg2png/seacloudR.png',
'/home/pi/Desktop/jpg2png/SeagleR.png'
]
  
         
if GPIO.input(document["bouton1"])==0:
       
  image_yatch = [
    '/home/pi/Desktop/jpg2png2/Ar.png',
'/home/pi/Desktop/jpg2png2/AntibeR.png',
'/home/pi/Desktop/jpg2png2/dubai.png',
'/home/pi/Desktop/jpg2png2/KHALILAHR.png',
'/home/pi/Desktop/jpg2png2/luxuy-yachtR.png',
'/home/pi/Desktop/jpg2png2/turquoiseR.png',
]





app = QApplication([])
if GPIO.input(document["bouton1"])==1:
    w = Diapo(image_voiliers)
if GPIO.input(document["bouton1"])==0:
    w = Diapo(image_yatch)

w.setGeometry(100, 100, 1200, 800)
w.show()
app.exec_()
Reply
#6
Start with this:
from PySide.QtCore import *
from PySide.QtGui import *
import RPi.GPIO as GPIO

import yaml

fichier = open("diaporama.yaml", "r")
document = yaml.load(fichier, Loader=yaml.Loader)

GPIO.setmode(GPIO.BOARD)
GPIO.setup(document["bouton1"],GPIO.IN,pull_up_down=GPIO.PUD_UP)
GPIO.setup(document["bouton2"],GPIO.IN,pull_up_down=GPIO.PUD_UP)

class Diapo(QWidget):
    def __init__(self, parent=None):
            super().__init__(self, parent)
            self.timer = QBasicTimer()
 
    def timerEvent(self, e=None):
        if GPIO.input(document["bouton2"])==1:
            print("bouton2 == 1")
        if GPIO.input(document["bouton2"])==0:
            print("bouton2 == 0")
 

app = QApplication([])
w = Diapo()
w.setGeometry(100, 100, 1200, 800)
w.show()
app.exec_()
Can you get this to print anything at all when you press the GPIO buttons?

Solve one problem at a time.
1. Get the GPIO buttons to do something when pressed.
2, Get the GPIO buttons to do something the correct number of times when pressed.
3. Get the GPIO buttons to do the correct thing the correct number of times when pressed.
4. Add in the slide show.
Reply
#7
At the start the first album slide than, if i press the bouton1 the second album shows up.
If i press bouon 2 while picture showing they will pause for 3 minutes.
I admit its not perfect but it works a little bit, i still have two weeks to find a permanent fix. Why modify bouton2 they work fine?
Its bouton1 the problem i thought about getting the album from a file and than apply choice of album with gpio. That would get me out of Pyside loop. What do you think?
Anyway now she want the pictures loaded from a file.
But that was not my question Wink
Reply
#8
I am pretty sure the buttons do not work since timerEvent only yuns when you press a soft button
Reply
#9
If i click button1 to switch the album its not working. It will switch only if the button is already press before i compile. For button2 if i press 5 seconds the pushbutton the image will freeze for 3 minutes. That part work. My question is it possible to move image_voiliers and image_yacht out of the scope of the class or the scope of the loop. I dont really understand why its not working. Cant solve what i dont understand.
If it is possible and extract the image from a file than i could use button1 gpio to choose with if statement between a image_voilier file or image_yatch file for example using io.
Reply
#10
You are trying to make the program work without understanding how all the different parts work. This approach hardly ever works. A carpenter that doesn't know how his tools work will build a crappy house. A programmer that doesn't understand the language or the libraries will write a crappy program.

To write this program you need to know the following:
1 How do I get input from GPIO
2 How do I debounce GPIO inputs
3 How do I map a change in GPIO input to a function

Start with #1.

This program uses the QTimer to update the display once a second. It displays the current data and time as well as the states of button1 and button2. Replace the random number with real code that reads the buttons and see if it displays the current button state. When hooked up to real buttons change the update to 100 times a second.
import PySide6.QtWidgets as QtWidgets  # I have PySide6.  Change to whatever PySide version you are using.
import PySide6.QtCore as QtCore
import random
from datetime import datetime
 
class Diapo(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        layout = QtWidgets.QVBoxLayout(self)
        self.time_label = QtWidgets.QLabel(self)
        self.button1_label = QtWidgets.QLabel(self)
        self.button2_label = QtWidgets.QLabel(self)
        layout.addWidget(self.time_label)
        layout.addWidget(self.button1_label)
        layout.addWidget(self.button2_label)

        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.timerEvent)
        self.timer.start(1000)
  
    def timerEvent(self):
        self.time_label.setText(datetime.now().strftime("%B %d, %I:%M:%S %p"))
        button1 = random.randint(0, 1) # replace with code that gets gpio buttons state
        button2 = random.randint(0, 1)
        self.button1_label.setText(str(button1)) 
        self.button2_label.setText(str(button2))
 
app = QtWidgets.QApplication([])
window = Diapo()
window.show()
app.exec_()
Try to figure out how you can modify this program to read the state of your buttons
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Pygame and tkinter seteg 1 1,508 Feb-14-2022, 12:04 PM
Last Post: dboxall123
  Pygame mixer and tkinter music player Kumarkv 1 2,747 May-14-2020, 06:08 PM
Last Post: Larz60+
  How can I use concurrency to migrate database in Python? binhduonggttn 4 2,550 Jan-31-2020, 09:25 AM
Last Post: buran
  Pygame*import pygame ImportError: No module named pygame CASPERHANISCH 1 9,763 Jun-05-2017, 09:50 PM
Last Post: nilamo
  Global Variables. Migrate code from MatLab Felipe 8 6,883 Jan-13-2017, 01:19 AM
Last Post: Felipe

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020