Related
I set the size in my panel, but it does not take action when I run the program. It just pops up small and I have to manually resize.
I have tried setting/initializing a frame, but when I do that it blocks any input. So I can no longer use my program. I have also tried numerous times to set it within the panel settings.
class CipherTexter(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent, size=(5000, 5000))
#wx.Frame.__init__(self, parent, size=(5000, 5000))
self.cipherText = wx.StaticText(self, label="Cipher Texter ", pos=(20, 30))
…
app = wx.App(False)
frame = wx.Frame(None, wx.ID_ANY, "The SS Cipher")
panel = CipherTexter(frame)
frame.Show()
app.MainLoop()
When I first open the application, I get this. I would like to be able to see the whole thing instead of having to manually resize it.
Try putting the "panel" within the "frame".
Here is a mock up of what is, I suppose, your required starting point.
import wx
class CipherTexter(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, title=title, size=(1000, 600))
self.panel = wx.Panel(self)
cipherText = wx.StaticText(self.panel, label="Cipher Texter ", pos=(20, 30))
encryptorText = wx.StaticText(self.panel, label="Encryptor ", pos=(20, 70))
decryptorText = wx.StaticText(self.panel, label="Decryptor ", pos=(20, 100))
self.cipher = wx.TextCtrl(self.panel, -1, style=wx.TE_MULTILINE, size=(400,400), pos=(400, 30))
self.encryptor = wx.TextCtrl(self.panel, -1, size=(100,30), pos=(200, 70))
self.decryptor = wx.TextCtrl(self.panel, -1, size=(100,30), pos=(200, 100))
self.encrypt = wx.Button(self.panel, -1, "Encrypt", pos=(20, 140))
self.decrypt = wx.Button(self.panel, -1, "Decrypt", pos=(20, 180))
self.panel.SetBackgroundColour('white')
self.encrypt.Bind(wx.EVT_BUTTON, self.encryptNow)
self.decrypt.Bind(wx.EVT_BUTTON, self.decryptNow)
self.Show()
def encryptNow(self, event):
print("Encrypting")
cipher = self.cipher.GetValue()
encryptor = self.encryptor.GetValue()
print(cipher)
print("with ", encryptor)
def decryptNow(self, event):
print("De-Encrypting")
cipher = self.cipher.GetValue()
decryptor = self.decryptor.GetValue()
print(cipher)
print("with ", decryptor)
app = wx.App(False)
frame = CipherTexter(None, "The SS Cipher")
app.MainLoop()
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.
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()
I have the code below which opens Quicktime via applescript and does stuff to files, which take a little while and mustn't be disturbed. I want a dialog window to open on top of everything else, not matter what it must stay on top, which just says "Processing files, please wait". This code works, but as soon as quicktime opens via applescript the PBI.PyBusyInfo disappears. Any idea how I could do this please?
import wx
import os
import os.path
import wx.lib.agw.pybusyinfo as PBI
from subprocess import Popen, PIPE
class ScrolledWindow(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(510, 370), style=wx.STAY_ON_TOP | wx.DEFAULT_FRAME_STYLE & ~ (wx.RESIZE_BORDER |
wx.RESIZE_BOX |
wx.MAXIMIZE_BOX))
self.tabbed = wx.Notebook(self, -1, style=(wx.NB_TOP))
run_params = {}
run_params["dropList1"] = ['HD 1920x1080', 'PAL 4x3', 'PAL 16x9', 'NTSC 4x3', 'NTSC 16x9']
run_params["dropList2"] = ['Progressive', 'Interlaced']
self.CreateStatusBar()
menuBar = wx.MenuBar()
menu = wx.Menu()
self.SetMenuBar(menuBar)
panel = wx.Panel(self, -1)
self.Centre()
self.Show()
self.filePrep = PrepFile(self.tabbed, run_params)
self.tabbed.AddPage(self.filePrep, "File Prep")
class PrepFile(wx.Panel):
def __init__(self, parent, run_params):
wx.Panel.__init__(self, parent)
self.run_params = run_params
self.fieldChoice = 'Progressive'
self.formatOption = 'HD 1920x1080'
outputOption = '''Format'''
wx.StaticText(self, -1, outputOption, (33, 22), style=wx.ALIGN_CENTRE)
self.choice1 = wx.Choice(self, pos=(35, 40), choices=self.run_params["dropList1"])
self.choice1.SetSelection(0)
self.choice1.SetFocus()
self.choice1.Bind(wx.EVT_CHOICE, self.selectOption)
fieldSetText = '''Fields'''
wx.StaticText(self, -1, fieldSetText, (33, 82), style=wx.ALIGN_CENTRE)
self.choice2 = wx.Choice(self, pos=(35, 100), choices=self.run_params["dropList2"])
self.choice2.SetSelection(0)
self.choice2.SetFocus()
self.choice2.Bind(wx.EVT_CHOICE, self.fieldSet)
self.buttonClose = wx.Button(self, -1, "Quit", pos=(195, 250))
self.buttonClose.Bind(wx.EVT_BUTTON, self.OnClose)
greyBox = wx.StaticBox(self, -1, '', pos=(20, 15), size=(235, 130))
outputtxt3 = '''Drag and Drop Quicktimes'''
wx.StaticText(self, -1, outputtxt3, pos=(35, 170), style=wx.ALIGN_CENTRE)
self.drop_target = MyFileDropTarget(self)
self.SetDropTarget(self.drop_target)
self.tc_files = wx.TextCtrl(self, wx.ID_ANY, pos=(38, 190), size=(200, 25))
self.buttonSubmit = wx.Button(self, -1, "Submit", pos=(250,190))
self.buttonSubmit.Bind(wx.EVT_BUTTON, self.submit)
def EvtRadioBox(self, event):
self.mode = (event.GetString())
def selectOption(self, e):
self.formatOption = self.choice1.GetStringSelection()
def fieldSet(self, e):
self.fieldChoice = self.choice2.GetStringSelection()
def setSubmissionDrop(self, dropFiles):
"""Called by the FileDropTarget when files are dropped"""
self.tc_files.SetValue(','.join(dropFiles))
self.selectedFiles = dropFiles
print self.selectedFiles
def submit(self, event):
event.Skip()
message = "Please wait..."
busy = PBI.PyBusyInfo(message, parent=self, title="Processing Files")
wx.Yield()
for item in self.selectedFiles:
if os.path.isdir(item):
print "It is a folder!"
for root, dirs, files in os.walk(item):
for file1 in files:
if file1.endswith(".mov"):
currentFile = os.path.join(root, file1)
self.jesFile(currentFile)
print "Finished"
del busy
def doSomething(self):
print "Open Quicktime and process files via applescript"
def OnClose(self, e):
CloseApp()
class MyFileDropTarget(wx.FileDropTarget):
""""""
def __init__(self, window):
wx.FileDropTarget.__init__(self)
self.window = window
def OnDropFiles(self, x, y, filenames):
self.window.setSubmissionDrop(filenames)
app = wx.App()
ScrolledWindow(None, -1, 'App')
app.MainLoop()
Your question seems to be missing the call where you start the AppleScript (it looks like you forgot to add the jesFile method to your example code). I can only speculate so much on your code that isn't in the posted example... but my guess is your call to do processing isn't a blocking call, so you either need to make it a blocking call, or save busy to a class variable that you delete when the non-blocking process call returns (hopefully you can bind a callback function for when that happens).
With my code, I've now decided that I need multiple screens to go between where the buttons and background will change
I think the easiest way for me to do that would be by defining panel classes, then creating one frame but I don't know how to link all the panels together on the frame. I know which buttons and images I want on each panel but I don't know how you define the panels and link them through a button click
import os
import pygame
import wx
import os
import game
class MainPanel(wx.Panel):
def __init__(self,parent,id):
image_file='main_screen.jpg'#loading an image file from the folder
bmp=wx.Bitmap(image_file)
self.bitmap = wx.StaticBitmap(self, wx.ID_ANY, bmp, (0, 0))
PlayButton=wx.Bitmap('play.jpg', wx.BITMAP_TYPE_ANY)
self.PlayButton=wx.BitmapButton(self.bitmap, -1, PlayButton, pos=(190,300))
self.PlayButton.Bind=(wx.EVT_BUTTON, self.opengame)
RulesButton=wx.Bitmap('rules.jpg', wx.BITMAP_TYPE_ANY)
self.RulesButton=wx.BitmapButton(self.bitmap, -1, RulesButton, pos=(190,370))
self.RulesButton.Bind=(wx.EVT_BUTTON, self.openrules)
ControlsButton=wx.Bitmap('controls.jpg', wx.BITMAP_TYPE_ANY)
self.ControlsButton=wx.BitmapButton(self.bitmap, -1, ControlsButton, pos=(190,440))
#self.ControlsButton.Bind=(wx.EVT_BUTTON, self.closeMe)
ExitButton=wx.Bitmap('exit.jpg', wx.BITMAP_TYPE_ANY)
self.ExitButton=wx.BitmapButton(self.bitmap,-1,ExitButton,pos=(190,510))
self.ExitButton.Bind(wx.EVT_BUTTON, self.closeexit)
self.Bind(wx.EVT_CLOSE, self.closewindow)
class ControlPanel(wx.Panel):
def __init__(self,parent,id):
wx.Panel.__init__(self, parent, id=wx.ID_ANY)
image_file='controls.jpg'#loading an image file from the folder
bmp=wx.Bitmap(image_file)
self.bitmap2 = wx.StaticBitmap(self, wx.ID_ANY, bmp, (0, 0))
BackButton=wx.Bitmap('back.jpg',wx.BITMAP_TYPE_ANY)
self.BackButton=wx.BitmapButton(self.bitmap2,-1,BackButton, pos=400,100)
self.BackButton.Bind=(wx.EVT_BUTTON, self.goback)
class RulesPanel(wx.Panel):
def __init__(self,parent,id):
wx.Panel.__init__(self, parent, id=wx.ID_ANY)
image_file='rules.jpg'#loading an image file from the folder
bmp=wx.Bitmap(image_file)
self.bitmap3 = wx.StaticBitmap(self, wx.ID_ANY, bmp, (0, 0))
BackButton=wx.Bitmap('back.jpg',wx.BITMAP_TYPE_ANY)
self.BackButton=wx.BitmapButton(self.bitmap3,-1,BackButton, pos=400,100)
self.BackButton.Bind=(wx.EVT_BUTTON, self.goback)
class MainFrame(wx.Frame):
def __init__(self,parent,id):
wx.Frame.__init__(self,parent,id,'Compsci Vs. Sheep: The Game',size=(640,640))
def openrules(self,event):
def opengame(self):
game.start()
def opencontrols(self,event):
?
def goback(self,event):
?
def closewindow(self,event):
self.Destroy()
pygame.mixer.quit()
def closeexit
if __name__=='__main__':
pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=4096)
pygame.mixer.music.load("exorcist.ogg")
pygame.mixer.music.play(-1)#music playing in program
app=wx.PySimpleApp()
frame=menu(parent=None,id=-1)
frame.Show()#shows the screen
app.MainLoop()
This is my new code which still doesn't work
import os
import pygame
import wx
def switch_to(name):
print "Pseudo switch",name
class MainFrame(wx.Frame):
def __init__(self,parent,id):
wx.Frame.__init__(self,parent,id,'Compsci Vs. Sheep: The Game',size=(640,640))
self.box = wx.BoxSizer()
self._panels = {}
self._panels['main'] = MainPanel(self, -1)
self._panels['rules'] = RulesPanel(self, -1)
self._panels['rules'].Hide()
self.box.Add(self._panels['main'],1,wx.EXPAND)
self.box.Add(self._panels['rules'],1,wx.EXPAND)
self.SetSizer(self.box)
def switch_panel(self, name):
print "Switching to",name
return
for key, panel in self._panels.iteritems():
if key != name:
panel.Hide()
else:
panel.Show(True)
self.Layout()
class MainPanel(wx.Panel):
def __init__(self,parent,id):
wx.Panel.__init__(self,parent,id=wx.ID_ANY)
image_file='main_screen.jpg'#loading an image file from the folder
bmp=wx.Bitmap(image_file)
self.bitmap = wx.StaticBitmap(self, wx.ID_ANY, bmp, (0, 0))
PlayButton=wx.Bitmap('play.jpg', wx.BITMAP_TYPE_ANY)
self.PlayButton=wx.BitmapButton(self,-1, PlayButton, (190,300), (244,60))
RulesButton=wx.Bitmap('rules.jpg', wx.BITMAP_TYPE_ANY)
self.RulesButton=wx.BitmapButton(self, -1, RulesButton, (190,300), (244,60))
self.RulesButton.Bind=(wx.EVT_BUTTON, parent.switch_panel)
class RulesPanel(wx.Panel):
def __init__(self,parent,id):
wx.Panel.__init__(self, parent, id=wx.ID_ANY)
image_file='rules.jpg'#loading an image file from the folder
bmp=wx.Bitmap(image_file)
self.bitmap = wx.StaticBitmap(self, wx.ID_ANY, bmp, (0, 0))
if __name__=='__main__':
pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=4096)
pygame.mixer.music.load("exorcist.ogg")
pygame.mixer.music.play(-1)#music playing in program
app = wx.PySimpleApp()
frame = MainFrame(parent=None,id=-1)
frame.Show()#shows the screen
app.MainLoop()
You could just create all the panels in your frame constructor and place them in a dictionary. Then you could create a function called switch_panel that hides all the panels except the one you wish to show. Example:
def MyFrame(wx.Frame):
# Dict for storing the panels.
_panels = {}
def __init__(self, parent, id):
wx.Frame.__init__(self, parent, id, 'Example')
# Create all the panels.
self._panels['main'] = MainPanel(self, -1)
self._panels['control'] = ControlPanel(self, -1)
self._panels['rules'] = RulesPanel(self, -1)
# Hide all the panels initially.
for key, panel in self._panels.iteritems():
panel.Hide()
# Show the main panel.
self.switch_panel('main')
def switch_panel(self, name):
"""Function for switching between the frame's panels."""
for key, panel in self._panels.iteritems():
if key != name:
panel.Hide()
else:
panel.Show(True)
Now any time you call switch_panel with "main", "control" or "rules", that panel will be shown and the others will be hidden.
How do I call switch_panel on a button click?
Bind an event handler to the button, e.g.
my_button = wx.Button(self, -1, 'Click me!')
my_button.bind(
wx.EVT_BUTTON,
lambda e: self.switch_panel('control')
)