Can someone please add an image as background to this program? (WXPython) - python

Yeah, I know... i had asked a lot today (And so many thanks, Furas!). But look, I just need one thing and it'll be done. Could some one, please, for the love of God, add and image as background to this program with WXPython? It does not matter what image you put. Just put a random image, is the only thing i need. Thanks.
#!/usr/bin/python
# -*- coding: utf-8 -*-
import wx, pygame, sys, random, os
from pygame.locals import *
from random import choice
from block import O, I, S, Z, L, J, T
class Example(wx.Frame):
def __init__(self, *args, **kwargs):
super(Example, self).__init__(*args, **kwargs)
self.InitUI()
def InitUI(self):
panel = wx.Panel(self)
hbox = wx.BoxSizer()
sizer = wx.GridSizer(2, 2, 2, 2)
btn1 = wx.Button(panel, label='Tetris')
btn2 = wx.Button(panel, label='Pong')
btn3 = wx.Button(panel, label='Brik')
sizer.AddMany([btn1, btn2, btn3])
hbox.Add(sizer, 150, wx.ALL, 200)
panel.SetSizer(hbox)
btn1.Bind(wx.EVT_BUTTON, self.Mensaje1)
btn2.Bind(wx.EVT_BUTTON, self.Mensaje2)
btn3.Bind(wx.EVT_BUTTON, self.Mensaje3)
self.SetSize((600, 500))
self.SetTitle('Messages')
self.Centre()
frame.Show(True)
def Mensaje1(self, event):
[stuffs...]
def Mensaje2(self, event):
[stuffs...]
def Mensaje3(self, event):
[stuffs...]
print "Hell, World"
def main():
ex = wx.App()
Example(None)
ex.MainLoop()
if __name__ == '__main__':
main()
Thanks again.

Use panel as a StaticBitmap's parent.
I removed some element to run this code.
import wx
class Example(wx.Frame):
def __init__(self, *args, **kwargs):
super(Example, self).__init__(parent=None, *args, **kwargs)
self.InitUI()
def InitUI(self):
panel = wx.Panel(self)
try:
self.image_filename = "roses.jpg"
self.image = wx.Image(self.image_filename, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
# parent: panel
self.bitmap = wx.StaticBitmap(panel, -1, self.image, (0, 0))
except IOError:
print "Image file %s not found" % self.image_filename
raise SystemExit
hbox = wx.BoxSizer()
panel.SetSizer(hbox)
btn1 = wx.Button(panel, label='Tetris')
btn2 = wx.Button(panel, label='Pong')
btn3 = wx.Button(panel, label='Brik')
sizer = wx.GridSizer(2, 2, 2, 2)
sizer.AddMany([btn1, btn2, btn3])
hbox.Add(sizer, 150, wx.ALL, 200)
self.SetSize((600, 500))
self.SetTitle('Messages')
self.Centre()
self.Show()
if __name__ == '__main__':
ex = wx.App()
Example() # I moved None to super.__init__
ex.MainLoop()

Related

Show a limited time Message wxPython

I build an application in wxPython and in the application I want to show a message for a limited time and then, it will be disappeared by itself (the user of the application doesn't have to nothing to make it disappear)
I tried to do it like that, but it didn't closed by itself.
dialog = wx.MessageDialog(None,'message', wx.OK | wx.ICON_INFORMATION | wx.STAY_ON_TOP)
threading.Timer(2.0, dialog.Destroy).start()
dialog.ShowModal()
I also tried to do it like that and it either didn't do nothing:
dialog = wx.MessageDialog(None,'message', wx.OK | wx.ICON_INFORMATION | wx.STAY_ON_TOP)
threading.Timer(2.0, dialog.EndModal,args=wx.ID_OK).start()
dialog.ShowModal()
I don't have enough context to see what is the problem with your timer. You could try this however.
import wx
# ================================================================================
class TimedDialog(wx.Dialog):
def __init__(self, *args, **kwargs):
super(TimedDialog, self).__init__(*args, **kwargs)
self.SetSize((400, 300))
self.SetTitle('Please wait!')
self.Centre()
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.OnTimer)
self.timer.Start(2000) # 2 second interval
def OnTimer(self, event):
self.Close()
# ================================================================================
class Example(wx.Frame):
def __init__(self, *args, **kwargs):
super(Example, self).__init__(*args, **kwargs)
self.InitUI()
def InitUI(self):
self.SetSize((300, 200))
self.SetTitle('app')
self.Centre()
self.btn = wx.Button(self, -1, "click Me")
self.btn.Bind(wx.EVT_BUTTON, self.OnClicked)
def OnClicked(self, event):
dlg = TimedDialog(self)
dlg.ShowModal()
def main():
app = wx.App()
ex = Example(None)
ex.Show()
app.MainLoop()
if __name__ == '__main__':
main()
I got your dialog to close using dialog.DestroyLater but it was not consistent, anywhere from on time to 20 seconds late. Hardly what you wanted.
This is something I put together 2 years ago but can no longer remember why.
It's a bit over the top but hopefully it will help.
import wx
class MyFrame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent, -1, "Busy Dialog",size=(500,200))
self.panel = wx.Panel(self)
sizer = wx.BoxSizer(wx.VERTICAL)
self.log = wx.TextCtrl(self.panel, wx.ID_ANY, size=(400,100),style = wx.TE_MULTILINE|wx.TE_READONLY|wx.VSCROLL)
self.button = wx.Button(self.panel, label="Click me")
sizer.Add(self.log, 0, wx.EXPAND | wx.ALL, 10)
sizer.Add(self.button, 0, wx.EXPAND | wx.ALL, 10)
self.panel.SetSizer(sizer)
self.Bind(wx.EVT_BUTTON, self.OnButton)
def OnButton(self,event):
dlg = Busy(parent = self.panel)
dlg.ShowModal()
if dlg.result_text:
self.log.AppendText("Text Input: "+dlg.result_text+"\n")
dlg.Destroy()
class Busy(wx.Dialog):
def __init__(self, parent):
wx.Dialog.__init__(self, parent, wx.ID_ANY, "Busy", size= (420,240))
self.panel = wx.Panel(self,wx.ID_ANY)
self.label = wx.StaticText(self.panel, label="Input", pos=(20,20))
self.textinput = wx.TextCtrl(self.panel, value="", pos=(80,20), size=(300,-1))
self.gauge = wx.Gauge(self.panel,size=(300,20),pos=(80,80), style=wx.GA_HORIZONTAL)
self.livelabel = wx.StaticText(self.panel, label="Time to live:", pos=(80,110))
self.lltime = wx.StaticText(self.panel, label="30", pos=(160,110))
self.saveButton =wx.Button(self.panel, label="Save Input", pos=(80,160))
self.closeButton =wx.Button(self.panel, label="Cancel", pos=(180,160))
self.timeoutButton =wx.Button(self.panel, label="Timer Off", pos=(280,160))
self.saveButton.Bind(wx.EVT_BUTTON, self.SaveBusyString)
self.closeButton.Bind(wx.EVT_BUTTON, self.OnQuit)
self.timeoutButton.Bind(wx.EVT_BUTTON, self.OnNoTimeout)
self.Bind(wx.EVT_CLOSE, self.OnQuit)
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER,self.OnTimer, self.timer)
self.lifetimer = wx.Timer(self)
self.Bind(wx.EVT_TIMER,self.OnLifeTimer, self.lifetimer)
self.timer.Start(100)
self.lifetimer.Start(1000)
self.timeoutbutton_pressed = False
self.gauge.SetBackgroundColour(wx.Colour(0, 127, 255, 255)) #Slate Blue
self.gauge.SetRange(100)
self.gauge.SetValue(0)
self.life = 30
self.direction = 1
self.result_text = None
self.Show()
def OnTimer(self, evt): #Update gauge
x = int(self.gauge.GetValue())
if x == 0:
self.direction = 1
elif x == 100:
self.direction = -1
x+=self.direction
self.gauge.SetValue(x)
def OnLifeTimer(self, evt): #Update time to live
if self.timeoutbutton_pressed == True:
return
self.life -= 1
self.lltime.SetLabelText(str(self.life))
if self.life < 1:
self.result_text = self.textinput.GetValue()
self.OnQuit(None)
def OnNoTimeout(self, evt): # toggle time to live
if self.timeoutbutton_pressed == False:
self.timeoutbutton_pressed = True
self.timeoutButton.SetLabel("Timer On")
else:
self.timeoutbutton_pressed = False
self.timeoutButton.SetLabel("Timer Off")
def OnQuit(self, event):
self.timer.Stop()
self.lifetimer.Stop()
self.Destroy()
def SaveBusyString(self, event): # return input
self.result_text = self.textinput.GetValue()
self.timer.Stop()
self.lifetimer.Stop()
self.Destroy()
app = wx.App()
frame = MyFrame(None)
frame.Show()
app.MainLoop()

wxPython Drag and Drop files onto image, to add to array

I have a simple wxPython application with 1 image "Drop files here!" and 2 buttons.
I want the user to be able to drag and drop files onto the top section/image, at which point the image changes and the files are loaded into an array.
That's all I need but I have hit a major roadblock getting the drag and drop to work. Can someone please take a look at my code and figure out how/where to integrate the Drag and drop event? Any help would be great.
UI image
import wx
class DropTarget(wx.FileDropTarget):
def OnDropFiles(self, x, y, filenames):
print(filenames)
image = Image.open(filenames[0])
image.thumbnail((PhotoMaxSize, PhotoMaxSize))
image.save('thumbnail.png')
pub.sendMessage('dnd', filepath='thumbnail.png')
return True
def __init__(self, parent, ID, title):
wx.FileDropTarget.__init__(self, parent, ID, title, size=(300, 340), style= wx.CLOSE_BOX)
#self.widget = widget
class MyFrame(wx.Frame):
def __init__(self, parent, ID, title):
wx.Frame.__init__(self, parent, ID, title, size=(300, 340), style= wx.CLOSE_BOX)
panel1 = wx.Panel(self,-1, style=wx.SUNKEN_BORDER)
panel2 = wx.Panel(self,-1, style=wx.SUNKEN_BORDER)
panel1.SetBackgroundColour("BLUE")
panel2.SetBackgroundColour("RED")
image_file = 'bgimage1.png'
bmp1 = wx.Image(
image_file,
wx.BITMAP_TYPE_ANY).ConvertToBitmap()
# image's upper left corner anchors at panel
# coordinates (0, 0)
self.bitmap1 = wx.StaticBitmap(
self, -1, bmp1, (0, 0))
# show some image details
str1 = "%s %dx%d" % (image_file, bmp1.GetWidth(),
bmp1.GetHeight())
# button
closeButton = wx.Button(self.bitmap1, label='Generate', pos=(30, 280))
closeButton.Bind(wx.EVT_BUTTON, self.OnClose)
clearButton = wx.Button(self.bitmap1, label='Clear', pos=(170, 280))
clearButton.Bind(wx.EVT_BUTTON, self.OnClose)
box = wx.BoxSizer(wx.VERTICAL)
box.Add(panel1, 5, wx.EXPAND)
box.Add(panel2, 1, wx.EXPAND)
self.SetAutoLayout(True)
self.SetSizer(box)
self.Layout()
def OnDropFiles(self, x, y, filenames):
self.window.updateDisplay(filenames)
for name in filenames:
self.window.WriteText(name + "\n")
print(name)
return True
def OnClose(self, e):
self.Close(True)
app = wx.App()
frame = MyFrame(None, -1, "Sizer Test")
frame.Show()
app.MainLoop()
You have the class DropTarget back to front with the init after the dropfiles. You also need to put the image and buttons on to one of the panels.
See below:
import wx
class DropTarget(wx.FileDropTarget):
def __init__(self, obj):
wx.FileDropTarget.__init__(self)
self.obj = obj
def OnDropFiles(self, x, y, filenames):
print("Drop Event",filenames)
# image = Image.open(filenames[0])
# image.thumbnail((PhotoMaxSize, PhotoMaxSize))
# image.save('new.png')
# pub.sendMessage('dnd', filepath='new.png')
return True
class MyFrame(wx.Frame):
def __init__(self, parent, ID, title):
wx.Frame.__init__(self, parent, ID, title, size=(300, 340))
panel1 = wx.Panel(self,-1, style=wx.SUNKEN_BORDER)
panel2 = wx.Panel(self,-1, style=wx.SUNKEN_BORDER)
panel1.SetBackgroundColour("BLUE")
panel2.SetBackgroundColour("RED")
image_file = 'bgimage1.png'
bmp1 = wx.Image(image_file,wx.BITMAP_TYPE_ANY).ConvertToBitmap()
self.bitmap1 = wx.StaticBitmap(panel1, -1, bmp1, (0, 0))
# button
closeButton = wx.Button(panel2, -1, label='Generate',pos=(30, 280))
closeButton.Bind(wx.EVT_BUTTON, self.OnClose)
clearButton = wx.Button(panel2, -1, label='Clear',pos=(170, 280))
clearButton.Bind(wx.EVT_BUTTON, self.OnClose)
self.file_drop_target = DropTarget(self)
self.SetDropTarget(self.file_drop_target)
box = wx.BoxSizer(wx.VERTICAL)
box.Add(panel1, 0, wx.EXPAND,0)
box.Add(panel2, 0, wx.EXPAND,0)
self.SetAutoLayout(True)
self.SetSizer(box)
self.Layout()
def OnClose(self, e):
self.Close(True)
app = wx.App()
frame = MyFrame(None, -1, "Sizer Test")
frame.Show()
app.MainLoop()
This may not be what you want to achieve but at least it's a startiing point and the drag and drop works.

How to delete an animated gif from a frame with wxPython?

I can't for the life of me figure out how to destroy or hide a gif from a wxPython frame.
Here is the example code:
import wx
import wx.animate
########################################################################
class MyForm(wx.Frame):
#----------------------------------------------------------------------
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "GIF frame")
panel = wx.Panel(self, wx.ID_ANY)
btn1 = wx.Button(self, -1, "Start GIF",(50,10))
btn1.Bind(wx.EVT_BUTTON, self.onButton1)
btn2 = wx.Button(self, -1, "Stop GIF",(50,40))
btn2.Bind(wx.EVT_BUTTON, self.onButton2)
#----------------------------------------------------------------------
def onButton1(self, event):
self.animateGIF()
#----------------------------------------------------------------------
def onButton2(self, event):
self.animateGIF(False)
#----------------------------------------------------------------------
def animateGIF(self, state=True):
gif_fname = "test.gif"
gif = wx.animate.GIFAnimationCtrl(self, -1, gif_fname,pos=(50,70),size=(10,10))
gif.GetPlayer()
if state:
gif.Play()
else:
gif.Stop()
#gif.Destroy(), gif.Hide() have no effect besides cancelling the Stop() function.
#----------------------------------------------------------------------
# Run the program
app = wx.App()
frame = MyForm().Show()
app.MainLoop()
So, how do I go about deleting this gif from my frame ?
Thank you! I hope the code is clear enough.
I believe you are loading a new GIF every time you call animateGIF. I suggest the following, though I am sure this can be improved:
import wx
import wx.animate
########################################################################
class MyForm(wx.Frame):
#----------------------------------------------------------------------
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "GIF frame")
# panel not used in this example
#panel = wx.Panel(self, wx.ID_ANY)
self.btn1 = wx.Button(self, -1, "Start GIF",(50,10))
self.btn1.Bind(wx.EVT_BUTTON, self.onButton1)
self.btn2 = wx.Button(self, -1, "Stop GIF",(50,40))
self.btn2.Bind(wx.EVT_BUTTON, self.onButton2)
self.gif = None
#----------------------------------------------------------------------
def onButton1(self, event):
self.animateGIF()
#----------------------------------------------------------------------
def onButton2(self, event):
self.animateGIF(False)
#----------------------------------------------------------------------
def animateGIF(self, state=True):
if self.gif == None:
gif_fname = "test.gif"
self.gif = wx.animate.GIFAnimationCtrl(self, -1, gif_fname,pos=(50,70),size=(10,10))
# call to GetPlayer was unnecessary
#gif.GetPlayer()
if state:
self.gif.Play()
else:
self.gif.Stop()
self.gif.Destroy()
self.gif = None
#----------------------------------------------------------------------
# Run the program
app = wx.PySimpleApp()
frame = MyForm().Show()
app.MainLoop()

pop up a window with text in it and automatically close it after certain time

This is the code that i have written. It does close the window but doesnt display the text in it. I need the text displayed and then automatic close of the window.
What changes should i make for it to work
Thanks
Here is the code
import wx
from time import sleep
class Frame(wx.Frame):
def __init__(self, title):
wx.Frame.__init__(self, None, title=title, size=(300,200))
self.panel = wx.Panel(self)
box = wx.BoxSizer(wx.VERTICAL)
m_text = wx.StaticText(self.panel, -1, 'File Uploaded!')
m_text.SetSize(m_text.GetBestSize())
box.Add(m_text, 0, wx.ALL, 10)
self.panel.SetSizer(box)
self.panel.Layout()
self.Bind(wx.EVT_ACTIVATE, self.onClose)
def onClose(self, event):
sleep(5)
self.Destroy()
app = wx.App(redirect=True)
top = Frame('test')
top.Show()
app.MainLoop()
I would recommend using a wx.Timer. If you use time.sleep(), you will block wxPython's main loop which makes your application unresponsive. Here is your code modified to use the timer:
import wx
class Frame(wx.Frame):
def __init__(self, title):
wx.Frame.__init__(self, None, title=title, size=(300,200))
self.panel = wx.Panel(self)
box = wx.BoxSizer(wx.VERTICAL)
m_text = wx.StaticText(self.panel, -1, 'File Uploaded!')
m_text.SetSize(m_text.GetBestSize())
box.Add(m_text, 0, wx.ALL, 10)
self.panel.SetSizer(box)
self.panel.Layout()
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.onClose, self.timer)
self.timer.Start(5000)
def onClose(self, event):
self.Close()
app = wx.App(redirect=True)
top = Frame('test')
top.Show()
app.MainLoop()
You can read more about timers in this article:
http://www.blog.pythonlibrary.org/2009/08/25/wxpython-using-wx-timers/
>>> import wx
>>> import time
>>> app = wx.App()
>>> b = wx.BusyInfo('Upload Finished!')
>>> time.sleep(5)
>>> del b
>>>

How can wxThumbnailCtrl in wxpython be used?

I think this is a new widget and theres no examples online about this. im not sure how i should start using it or how it can be used.
Here is simple example to get you started. self.button selects directory with images; on doubleclick on any of thumbnails a messagebox is shown with info on selected thumb.
import wx
from wx.lib.agw import thumbnailctrl as tn
class MyFrame(wx.Frame):
def __init__(self, *args, **kwds):
wx.Frame.__init__(self, *args, style=wx.DEFAULT_FRAME_STYLE)
self.button = wx.Button(self, -1, "Select dir")
self.Bind(wx.EVT_BUTTON, self.ButtonPress, self.button)
self.tn = tn.ThumbnailCtrl(self)
self.tn.Bind(tn.EVT_THUMBNAILS_DCLICK, self.TnClick)
box = wx.BoxSizer(wx.VERTICAL)
box.Add(self.tn, 1, wx.EXPAND, 0)
box.Add(self.button, 0, wx.ADJUST_MINSIZE, 0)
self.SetSizer(box)
box.Fit(self)
self.Layout()
def ButtonPress(self, evt):
dlg = wx.DirDialog(self, 'Get dir')
if dlg.ShowModal() == wx.ID_OK:
path = dlg.GetPath()
dlg.Destroy()
self.tn.ShowDir(path)
def TnClick(self, evt):
sel = self.tn.GetSelection()
wx.MessageBox(self.tn.GetThumbInfo(sel))
if __name__ == "__main__":
app = wx.PySimpleApp(0)
frame = MyFrame(None, -1, "")
frame.Show()
app.MainLoop()

Categories

Resources