i am stuck with PYTHON PYGAME
and need a popup window / or MENU to allow a user to select a ( existing) file from the filesystem.
anybody has a ready code?
Re: pygame file dialog
I guess using TkInter instead is the easeist option ... not very beautiful , though .
http://stackoverflow.com/questions/1832 ... for-a-file
ghans
http://stackoverflow.com/questions/1832 ... for-a-file
ghans
• Don't like the board ? Missing features ? Change to the prosilver theme ! You can find it in your settings.
• Don't like to search the forum BEFORE posting 'cos it's useless ? Try googling : yoursearchtermshere site:raspberrypi.org
• Don't like to search the forum BEFORE posting 'cos it's useless ? Try googling : yoursearchtermshere site:raspberrypi.org
Re: pygame file dialog
You should have a look at PGU (Phils pyGame Utilities)
http://www.pygame.org/project-PGU+-+Phi ... 8-471.html
It has a range of GUI elements including a file open dialog.
http://www.pygame.org/project-PGU+-+Phi ... 8-471.html
It has a range of GUI elements including a file open dialog.
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter
Pi Interests: Home Automation, IOT, Python and Tkinter
Re: pygame file dialog
thanks, i will check on both,
but i had already bad luck with mixing PYGAME and Tkinter
as a Tkinter dialog is it exactly the same as with the Python 2 IDE File open
see attachment, nice.
but i started with the gtk ( mixed / called from PYGAME )
and i am not able to close the dialog, but it actually works to choose a file.
possibly only one "smart" line of code missing.
that one looks like the new filemanager PCManFM
see attachment (low quality!)
there must be a way that it is not needed to mix the various GUIs.
but i had already bad luck with mixing PYGAME and Tkinter
as a Tkinter dialog is it exactly the same as with the Python 2 IDE File open
see attachment, nice.
but i started with the gtk ( mixed / called from PYGAME )
and i am not able to close the dialog, but it actually works to choose a file.
possibly only one "smart" line of code missing.
that one looks like the new filemanager PCManFM
see attachment (low quality!)
Code: Select all
#KLL
# gtk dialog from github majorsilence pygtknotebook
# KLL 15.01.2015
# search button
# result:
# if window open: "!open"
# if window closed "!close"
# if button [Cancel] "!cancel"
# if button [Open] or double click on file "/path/filename"
import pygtk
pygtk.require('2.0')
import gtk
import sys
import os
import pygame
from pygame.locals import *
import subprocess
import getopt
mytitle="fileopenwindow_pygame.py"
WINDOWWIDTH = 380 # size of window's width in pixels
WINDOWHEIGHT =240 # size of windows' height in pixels
# show text
msg=""
ipady = 5
ipadx = 10
# button
buttonmsg = "search"
ibuttonwide = 60
ibuttonhigh = 17
ipadbuttony = WINDOWHEIGHT - ibuttonhigh -10
ipadbuttonx = WINDOWWIDTH - ibuttonwide -10
unselborder = 1
selborder = 3
FPS = 20 # frames per second, the general speed of the PYGAME program
WHITE = (255, 255, 255)
BLACK = ( 0, 0, 0)
GREY = (125, 125, 125)
PURPLE = (255, 0, 255)
CYAN = ( 0, 255, 255)
RED = (255, 0, 0)
GREYLIGHT = (100, 100, 100)
unselcol = GREYLIGHT
selcol = GREY
mousex = 0 # used to store x coordinate of mouse event
mousey = 0 # used to store y coordinate of mouse event
filename = ""
#______________________________________________________________________
def draw_msg():
info="filename:"
myfont = pygame.font.SysFont("monospace",11,bold=True)
DISPLAYSURF.blit(myfont.render(info,1,BLACK,WHITE),(ipadx,ipady))
myfont = pygame.font.SysFont("monospace",12,bold=True)
DISPLAYSURF.blit(myfont.render(msg,1,PURPLE,WHITE),(ipadx,ipady+20))
#______________________________________________________________________
def draw_button():
# START button
bord= unselborder
bcol = unselcol
myfont = pygame.font.SysFont("monospace",16,bold=True)
pygame.draw.rect(DISPLAYSURF, bcol,(ipadbuttonx-bord-1, ipadbuttony-bord-1,ibuttonwide+2*bord+2,ibuttonhigh+2*bord+2),bord)
DISPLAYSURF.blit(myfont.render(buttonmsg,1,WHITE,BLACK),(ipadbuttonx,ipadbuttony))
#______________________________________________________________________
def sel_button(x, y):
# START button under mouse
boxRect = pygame.Rect(ipadbuttonx,ipadbuttony,ibuttonwide,ibuttonhigh)
if boxRect.collidepoint(x, y):
bord=selborder
bcol = selcol
pygame.draw.rect(DISPLAYSURF,bcol, (ipadbuttonx - bord-1, ipadbuttony - bord-1, ibuttonwide + 2*bord+2,ibuttonhigh + 2*bord+2), bord)
return True
return False
#______________________________________________________________________
def opendlg():
global filename
#file filters used with the filechoosers
text_filter=gtk.FileFilter()
text_filter.set_name("Text files")
text_filter.add_mime_type("text/*")
all_filter=gtk.FileFilter()
all_filter.set_name("All files")
all_filter.add_pattern("*")
dialog=gtk.FileChooserDialog(title="Select a File", action=gtk.FILE_CHOOSER_ACTION_OPEN, buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))
if (text_filter != None) and (all_filter != None):
dialog.add_filter(text_filter)
dialog.add_filter(all_filter)
filename = "!close"
response = dialog.run()
if response == gtk.RESPONSE_OK:
filename = dialog.get_filename()
elif response == gtk.RESPONSE_CANCEL:
filename = "!cancel"
dialog.destroy() # does not to close the frozen window
# but a second call of the dialog closes the old and open a new one
#sys.exit(filename) # both window close
#gtk.main() # the select window closes but mymain freezes
#gtk.main_quit() # error
#______________________________________________________________________
def mymain():
global DISPLAYSURF,msg
global filename
pygame.init()
FPSCLOCK = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption(mytitle)
DISPLAYSURF.fill(WHITE)
draw_button()
pygame.display.update()
FPSCLOCK.tick(FPS)
mousex = 0 # used to store x coordinate of mouse event
mousey = 0 # used to store y coordinate of mouse event
while True:
mouseClicked = False
DISPLAYSURF.fill(WHITE)
draw_button()
draw_msg()
for event in pygame.event.get():
if event.type == QUIT: # close window[x] QUIT event
pygame.display.quit()
pygame.quit()
sys.exit()
elif event.type == MOUSEMOTION:
mousex, mousey = event.pos
elif event.type == MOUSEBUTTONDOWN:
mousex, mousey = event.pos
mouseClicked = True
if ( sel_button(mousex, mousey)) :
if ( mouseClicked ) :
opendlg() # waiting
msg=filename
print "i got a filename: %s" % (msg)
pygame.display.update()
FPSCLOCK.tick(FPS)
pygame.display.quit()
pygame.quit()
#sys.exit()
if __name__ == "__main__":
mymain()
gtk.main()
- Attachments
-
- gtk dialog
- SNAG-0017.jpg (24.97 KiB) Viewed 6095 times
-
- Tkinter dialog
- SNAG-0014.jpg (24.24 KiB) Viewed 6096 times
Last edited by KLL on Fri Jan 16, 2015 4:16 am, edited 2 times in total.
Re: pygame file dialog
ok, here is a "BAD ASS" trick: the PYTHON gurus will hate me for that
the python gtk file open dialog is a stand alone program
and saves the result to a RAM DISK file.
any main program can call that program and evaluate the result by reading the file
-a- example PYTHON Tkinter
-b- example PYTHON PYGAME
the python gtk file open dialog is a stand alone program
and saves the result to a RAM DISK file.
Code: Select all
#/pytho_audio/file_open/fileopenwindow.py
# from github majorsilence pygtknotebook
# KLL 16.01.2015
# start terminal or suprocess : python fileopenwindow.py
# result:
# there is a file in /run/shm/filechoose.txt
# it contains:
# if window open: "!open"
# if window closed "!close"
# if button [Cancel] "!cancel"
# if button [Open] or double click on file "/path/filename"
import pygtk
pygtk.require('2.0')
import gtk
import sys
import os
def save_to_file(fileline="") :
if os.name == 'posix': # RPI linux
RAMDISKpath = '/run/shm/'
else :
RAMDISKpath = 'C:/tmp/'
sfiledata = RAMDISKpath+"filechoose.txt"
fdat = open(sfiledata,"w")
fdat.write(fileline+"\n")
fdat.close()
def main():
#file filters used with the filechoosers
text_filter=gtk.FileFilter()
text_filter.set_name("Text files")
text_filter.add_mime_type("text/*")
all_filter=gtk.FileFilter()
all_filter.set_name("All files")
all_filter.add_pattern("*")
filename=None
save_to_file("!open") # open the file in ramdisk for masterprogram to check
dialog=gtk.FileChooserDialog(title="Select a File", parent=None, action=gtk.FILE_CHOOSER_ACTION_OPEN, buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK))
#dialog.connect("delete-event",gtk.main_quit)
if (text_filter != None) and (all_filter != None):
dialog.add_filter(text_filter)
dialog.add_filter(all_filter)
filename = "!close"
response = dialog.run()
if response == gtk.RESPONSE_OK:
filename = dialog.get_filename()
#print "File Choosen: ", filename
elif response == gtk.RESPONSE_CANCEL:
filename = "!cancel"
#print 'Cancel Clicked'
save_to_file(filename)
dialog.destroy()
sys.exit(filename) # prints the "filename" OR "!cancel" after all that stupid gtk warnings in terminal window
# but if you click window[x] get nothing!
if __name__ == "__main__":
main()
-a- example PYTHON Tkinter
Code: Select all
# gtk dialog from github majorsilence pygtknotebook
# KLL 16.01.2015
# search button
# result:
# there is a file in /run/shm/filechoose.txt
# it contains:
# if window open: "!open"
# if window closed "!close"
# if button [Cancel] "!cancel"
# if button [Open] or double click on file "/path/filename"
import sys
import os
import subprocess
from Tkinter import *
master = Tk()
mytitle="Tkinter_call_gtkdlg.py"
master.title(mytitle)
# you need the gtk file open dialog program, where is it?
fowpy = "fileopenwindow.py"
WINDOWWIDTH = 380 # size of window's width in pixels
WINDOWHEIGHT =240 # size of windows' height in pixels
filename = ""
#______________________________________________________________________
def read_from_file() :
global filename
if os.name == 'posix': # RPI linux
RAMDISKpath = '/run/shm/'
else :
RAMDISKpath = 'C:/tmp/'
sfiledata = RAMDISKpath+"filechoose.txt"
try:
fdat = open(sfiledata,"r")
filename = fdat.readline()
filename = filename.strip()
#print filename
fdat.close()
except:
filename = "!error"
print "file ERROR"
return()
#______________________________________________________________________
def opendlg():
global filename,fowpy
subprocess.call(['python',fowpy])
read_from_file() # sets filename variable
# here evaluate on !error !close !open !cancel
# or do something with the file
pass
# update info
msg=filename
varmsgf.set(msg)
# show window with text and button
winframe = Frame(master,height=WINDOWHEIGHT, width=WINDOWWIDTH)
winframe.pack()
# show text
msg="filename:"
ipady = 5
ipadx = 10
varmsg=StringVar()
info=Label(winframe, textvariable=varmsg, bg="#FFFFFF")
varmsg.set(msg)
info.place(x=ipadx,y=ipady)
msg=filename
ipady = 5+ 20
ipadx = 10
varmsgf=StringVar()
infof=Label(winframe, textvariable=varmsgf, bg="#FFFFFF", fg="#CC0099")
varmsgf.set(msg)
infof.place(x=ipadx,y=ipady)
# button
buttonmsg = "search"
ibuttonwide = 60
ibuttonhigh = 17
ipadbuttony = WINDOWHEIGHT - ibuttonhigh -10
ipadbuttonx = WINDOWWIDTH - ibuttonwide -10
mybutton =Button(winframe, text=buttonmsg, command=opendlg )
mybutton.place(x=ipadbuttonx,y=ipadbuttony)
#______________________________________________________________________
def mymain():
global master,msg
global filename
master.mainloop()
if __name__ == "__main__":
mymain()
-b- example PYTHON PYGAME
Code: Select all
# gtk dialog from github majorsilence pygtknotebook
# KLL 15.01.2015
# search button
# result:
# there is a file in /run/shm/filechoose.txt
# it contains:
# if window open: "!open"
# if window closed "!close"
# if button [Cancel] "!cancel"
# if button [Open] or double click on file "/path/filename"
import sys
import os
import pygame
from pygame.locals import *
import subprocess
import getopt
# you need the gtk file open dialog program, where is it?
fowpy = "fileopenwindow.py"
mytitle="pygame_call_gtkdlg.py"
WINDOWWIDTH = 380 # size of window's width in pixels
WINDOWHEIGHT =240 # size of windows' height in pixels
# show text
msg=""
ipady = 5
ipadx = 10
# button
buttonmsg = "search"
ibuttonwide = 60
ibuttonhigh = 17
ipadbuttony = WINDOWHEIGHT - ibuttonhigh -10
ipadbuttonx = WINDOWWIDTH - ibuttonwide -10
unselborder = 1
selborder = 3
FPS = 20 # frames per second, the general speed of the PYGAME program
WHITE = (255, 255, 255)
BLACK = ( 0, 0, 0)
GREY = (125, 125, 125)
PURPLE = (255, 0, 255)
CYAN = ( 0, 255, 255)
RED = (255, 0, 0)
GREYLIGHT = (100, 100, 100)
unselcol = GREYLIGHT
selcol = GREY
mousex = 0 # used to store x coordinate of mouse event
mousey = 0 # used to store y coordinate of mouse event
filename = ""
#______________________________________________________________________
def draw_msg():
info="filename:"
myfont = pygame.font.SysFont("monospace",11,bold=True)
DISPLAYSURF.blit(myfont.render(info,1,BLACK,WHITE),(ipadx,ipady))
myfont = pygame.font.SysFont("monospace",12,bold=True)
DISPLAYSURF.blit(myfont.render(msg,1,PURPLE,WHITE),(ipadx,ipady+20))
#______________________________________________________________________
def draw_button():
# START button
bord= unselborder
bcol = unselcol
myfont = pygame.font.SysFont("monospace",16,bold=True)
pygame.draw.rect(DISPLAYSURF, bcol,(ipadbuttonx-bord-1, ipadbuttony-bord-1,ibuttonwide+2*bord+2,ibuttonhigh+2*bord+2),bord)
DISPLAYSURF.blit(myfont.render(buttonmsg,1,WHITE,BLACK),(ipadbuttonx,ipadbuttony))
#______________________________________________________________________
def sel_button(x, y):
# START button under mouse
boxRect = pygame.Rect(ipadbuttonx,ipadbuttony,ibuttonwide,ibuttonhigh)
if boxRect.collidepoint(x, y):
bord=selborder
bcol = selcol
pygame.draw.rect(DISPLAYSURF,bcol, (ipadbuttonx - bord-1, ipadbuttony - bord-1, ibuttonwide + 2*bord+2,ibuttonhigh + 2*bord+2), bord)
return True
return False
#______________________________________________________________________
def save_to_file(fileline="") :
if os.name == 'posix': # RPI linux
RAMDISKpath = '/run/shm/'
else :
RAMDISKpath = 'C:/tmp/'
sfiledata = RAMDISKpath+"filechoose.txt"
fdat = open(sfiledata,"w")
fdat.write(fileline+"\n")
fdat.close()
#______________________________________________________________________
def read_from_file() :
global filename
if os.name == 'posix': # RPI linux
RAMDISKpath = '/run/shm/'
else :
RAMDISKpath = 'C:/tmp/'
sfiledata = RAMDISKpath+"filechoose.txt"
try:
fdat = open(sfiledata,"r")
filename = fdat.readline()
filename = filename.strip()
#print filename
fdat.close()
except:
filename = "!error"
print "file ERROR"
return()
#______________________________________________________________________
def opendlg():
global filename,fowpy
subprocess.call(['python',fowpy])
read_from_file() # sets filename variable
# here evaluate on !error !close !open !cancel
# or do something with the file
pass
#______________________________________________________________________
def mymain():
global DISPLAYSURF,msg
global filename
pygame.init()
FPSCLOCK = pygame.time.Clock()
DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption(mytitle)
DISPLAYSURF.fill(WHITE)
draw_button()
pygame.display.update()
FPSCLOCK.tick(FPS)
mousex = 0 # used to store x coordinate of mouse event
mousey = 0 # used to store y coordinate of mouse event
while True:
mouseClicked = False
DISPLAYSURF.fill(WHITE)
draw_button()
draw_msg()
for event in pygame.event.get():
if event.type == QUIT: # close window[x] QUIT event
pygame.display.quit()
pygame.quit()
sys.exit()
elif event.type == MOUSEMOTION:
mousex, mousey = event.pos
elif event.type == MOUSEBUTTONDOWN:
mousex, mousey = event.pos
mouseClicked = True
if ( sel_button(mousex, mousey)) :
if ( mouseClicked ) :
opendlg() # waiting
msg=filename
#print "i got a filename: %s" % (msg)
pygame.display.update()
FPSCLOCK.tick(FPS)
pygame.display.quit()
pygame.quit()
#sys.exit()
if __name__ == "__main__":
mymain()