using time.sleep in wxPython - python

Using time.sleep in my wxPython code just after re-positioning a bitmapbutton caused my button to go totally blank. Just a white space was left in the region where the button should have been. Can any one please explain the reason and suggest any solution? Here's my code:
import wx
import time
class gui(wx.Frame):
def __init__(self,parent,id):
wx.Frame.__init__(self,parent,id,'New Window',pos=(0,0),size=wx.DisplaySize())
panel=wx.Panel(self)
self.SetBackGroundColour('green')
self.pic=wx.BitmapButton(self,-1,wx.Image("Candle.jpg",wx.BITMAP_TYPE_ANY).ConvertToBitmap(),pos=(700,300))
self.Bind(wx.EVT_BUTTON,self.position,self.pic)
def positon(self,event):
self.pic.Hide()
self.pic=wx.BitmapButton(self,-1,wx.Image("Candle.jpg",wx.BITMAP_TYPE_ANY).ConvertToBitmap(),pos=(700,300))
time.sleep(2)
self.pic.Hide()
if __name__=='__main__':
app=wx.PySimpleApp()
frame=gui(None,-1)
frame.Show()
app.MainLoop()

Well there's no wonder your button goes blank, you've pretty much programmed it to do so.
self.pic.Hide() => hides the button
self.pic=wx.BitmapButton(self,-1,wx.Image("Candle.jpg",wx.BITMAP_TYPE_ANY).ConvertToBitmap(),pos=(700,300)) => displays the button once again
time.sleep(2) => takes a brake for 2 seconds
self.pic.Hide() => hides the button again
The conclusion is, your button won't show up. So I don't see what's the problem, as it does exactly what you programmed it to.

time.sleep() blocks wx's mainloop and makes the GUI unresponsive for however long you've told it to sleep. There are several alternatives. You can use a wx.Timer or use threads (or similar). I think using a Timer makes more sense in your use case though.

well it depends, was time sleep used in the button's event ?, cause I believe if it was it's because of that. The button waits for the event it triggered to end so it would go back to its initial state.

sleep is blocking, so execution is stuck in your position method for two seconds and is unable to return to the MainLoop to process other events, like painting your changes to the screen. After the two seconds are up the image is hidden, but was never drawn.
To get the effect you want you'll have to start a timer, and bind the timer to a handler which can show the StaticBitmap again.
By the way you can also call Show again rather than creating a new control, and it's parent should also be the panel, not the frame.

Related

How to execute a command with a button and delete it before the command ends ? Python / Tkinter

I've got an interface where there is a 'Start' button. It runs a 'main' command where it starts a loop to run some measurements on a powermeter. I want to be able to click on an 'OK' button every time the measure is ready to be done. This button would replace the 'Start' button.
But when I try to destroy the button (buttonStart.destroy()) and then run the command main()
, the command executes but doesn't delete the button until the very end.
I've tried using threads from threading package, but it doesn't really work.
If there is a way to both destroy the button and run a command, I would be very interested !
Thanks a lot
The event loop must be given the opportunity to process events in order for the window to be removed from the screen.
There are a couple of ways to make that happen. The first is to call the update_idletasks method on any widget. That is usually enough to process the event related to the destruction of the widget, though it may be necessary to call update instead. Calling update should be avoided if at all possible. My rule of thumb is to start with update_idletasks. If that doesn't work, switch to update or switch to using after.
def my_custom_function():
startButton.destroy()
root.upddate_idletasks()
main()
The second method is to run your main function via after or after_idle. This will let tkinter naturally process all pending events before starting main. I would argue that this is the best approach. I recommend trying after_idle first, and if that doesn't work, switch to after with a small delay.
def my_custom_function():
startButton.destroy()
root.after_idle(main)

Tkinter code runs without mainloop, update, or after

I have been trying to use tkinter to make a gui to select some excel files and sheets from those files.
I have a lot of experience in python, but I'd probably say a novice at tkinter.
The code I have written to select the files is shown below (typos are likely because I cannot access the internet on the machine these files are on, so I am typing it up here).
My question is about mainloop(), the update functions, and after(). I had mainloop() at the end of my code, but my program wouldn't terminate (i.e. the terminal would remain) after it did what it does. So I removed the mainloop() and now it functions perfectly without any mainloop(), update(), or after() calls.
I don't really understand this and would really like to. I get that mainloop() stops the code from progressing until the root closes, but I thought nothing would show up without mainloop(), and this code does wait for the user to close the windows before continuing.
I was also wondering if I do not have mainloop (or the like), the code still closes fine whether or not I have root.destroy() at the end of the App class (commented in the code). I don't get that either.
This information would help me make better and correct code in the future and hopefully improve this one. FYI, I have searched for the answer to this everywhere and could not find one, at least one I could understand. Thanks a bunch.
This is as minimal as I can think of for this code.
Code (Edited from original post):
import tkinter as tk
from tkinter import ttk
class App:
def __init__(self, parent):
self.root = parent
self.root.withdraw()
tl = tk.Toplevel(parent)
b = ttk.Button(tl, text="Test widget")
b.grid()
tl.wait_window()
# This line does not change how the code functions at all
#self.root.destroy()
def run(self):
# Whether or not this is a function in the class or called globally doesn't matter.
self.root.mainloop()
if __name__ == "__main__":
root = tk.Tk()
app = App(root)
# This is the mainloop() call. If I include it, the program does not close after
# running the code in App.__init__. Without it, it runs perfectly.
# app.run()
mainloop enters an event listening loop for your tk.Tk() application.
You should create only one object with Tk() in every tkinter application.
Now this loop will "globally" listen for GUI events and will call your registered callbacks (event handlers). Code before the mainloop call will run but nothing will be shown or updated in the screen until you call it. No event (user input, mouse movement, keyboard and others) will be queued and responded to before that. But the widgets are created and configured, just not shown yet. If you call root.update() without ever entering the mainloop you will eventually see the window flash and disappear because everything is running, and you force window refresh, but then suddenly the program ends.
So configure your GUI and in the end always run root.mainloop()
Now when you call wait_window, you are creating a local event loop (and blocking the mainloop if it was running). For a perfect explanation of wait_window by Brian see here
What happened to you is that your app is happily running with your local event loop, but without mainloop. That would be a strange thing to do. Even if you are making as Brian explains, a modal window, you want to "return" to the mainloop after the window closes.
As for the after method it just registers a callback function to run after your choosen time, or after the mainloop becames idle, with after_idle (nothing more to refresh, no events in the queue..., also think as soon as possible). And if you want to re-run that function again in the same way it should re-register with after or after_idle before returning.
So always use your mainloop() ending call - or should I say event loop starting call :)
Edit:
Also, don't do things in your code that are slow, or that may block the loops, such as calling sleep or any other blocking function. That will freeze the GUI, until the block ends.

Tkinter Placing And Deleting A Label

I'm trying to display a message saying "Hi"
after a couple seconds, i want that message to go away and open a different file
https://hastebin.com/uhafehizok.vbs
so if its true I want it to place the label, wait two seconds, and then destroy it, but the Tkinter window is waiting two seconds to start, and then starting without any label
any ideas
In your code, the label is placed, and after 2 seconds it is destroyed. It is never actually shown in your window however as it is not updated.
This is as when entering Tk's mainloop, it updates the window in a loop, checking if changes have been made. In your case, you are preventing this check by using time.sleep.
With Tkinter, when wanting to have timings you should always use the after method, to arrange everything in terms of Tkinter's mainloop (This uses milliseconds).
To fix your code, you could add root.update() after placing your label. The time.sleep would still freeze up the mainloop whilst it is waiting however, so a better solution would be to remove the call to sleep, and instead call destroy on your label after 2 seconds.
This would look like root.after(2000, letsgolabel.destroy).
*Note that I have been referring to root as your access to tk.Tk(), as this is normally used.

Tkinter method deiconify seems not working on ubuntu(12.04, unity)

Tkinter method "deiconify" seems not working on ubuntu(12.04, unity), but the the following code works as expected on windows 7. I need to show the window even it is minimized when something happens in another project https://github.com/thinker3/youdao.
from time import sleep
from Tkinter import Tk
class GUI():
def __init__(self):
self.root = Tk()
self.root.title("Test")
self.root.protocol("WM_DELETE_WINDOW", self.close_handler)
self.root.mainloop()
def close_handler(self):
self.root.iconify()
sleep(1)
self.root.deiconify()
if __name__ == '__main__':
gui = GUI()
What you are seeing is apparently the difference between Windows and non-Windows. It looks to me like the Windows behavior is a bug. At the very least, it's not expected behavior. What you are seeing on ubuntu is what I would expect to see.
For a GUI to do anything, the event loop must be running. Everything that happens is the response to an event. The drawing of a window on the screen is a response to an event. A button click is a response to an event. The visual effect of a button being pressed is a response to an event. And so on.
When you call iconify, that causes an event to be sent to the app saying "remove the window from the screen". The event loop sees the event, and redraws (or "un"draws) the window. The reverse happens when you call deiconify -- the system gets a redraw event, and tkinter redraws the window on the screen.
In your code, you never give the event loop a chance to respond to these events. You ask it to iconfiy, then you sleep, then you deiconify, all without giving the event loop a chance to respond. While the sleep command is running no events are processed. So, when you wake from sleep, the system hides the window, and then microseconds later it redraws it.
What is probably happening on windows is that the window manager is getting the iconfiy command and removing the window without tkinter's involvement. In other words, tkinter doesn't actually do anything to make it go away. On X11-based systems, however, this is all managed by the event loop.
If you want the window to go away, and a second later reappear, use the event loop to your advantage. Allow the event loop to update the screen, and arrange for the deiconify to happen at sometime in the future. For example:
def close_handler(self):
self.root.iconify()
self.after(1000, self.root.deiconify)
This should work on all platforms. It allows the event loop to respond to the iconify event, and then a second later the deiconify command will run.

Qt - Temporarily disable all events or window functionality?

I have a Qt program with many buttons, user-interactable widgets, etc.
At one stage in the program, I would like all the widgets to temporarily 'stop working'; stop behaving to mouse clicks and instead pass the event on to one function.
(This is so the User can select a widget to perform meta operations. Part explanation here: Get variable name of Qt Widget (for use in Stylesheet)? )
The User would pick a widget (to do stuff with) by clicking it, and of course clicking a button must not cause the button's bound function to run.
What is the correct (most abstracted, sensible) method of doing this?
(which doesn't involve too much new code. ie; not subclassing every widget)
Is there anything in Qt designed for this?
So far, I am able to retrieve a list of all the widgets in the program (by calling
QObject.findChildren(QtGui.QWidget)
so the solution can incorporate this.
My current horrible ideas are;
Some how dealing with all the applications events all the time in one
function and not letting through the events when I need the
application to be dormant.
When I need dormancy, make a new transparent widget which recieves
mouse clicks and stretch it over the entire window. Take coordinates
of click and figure out the widget underneath.
Somehow create a new 'shell' instance of the window.
THANKS!
(Sorry for the terrible write-up; in a slight rush)
python 2.7.2
PyQt4
Windows 7
You can intercept events send to specific widgets with QObject::installEventFilter.
graphite answered this one first so give credit where credit is due.
For an actual example in PySide, here's an example you might draw some useful code from:
my_app.py
from KeyPressEater import KeyPressEater
if __name__ == "__main__":
app = QApplication(sys.argv)
eater = KeyPressEater()
app.installEventFilter(eater)
KeyPressEater.py
class KeyPressEater(QObject):
# subclassing for eventFilter
def eventFilter(self, obj, event):
if self.ignore_input:
# swallow events
pass
else:
# bubble events
return QObject.eventFilter(self,obj,event)

Categories

Resources