wxPython: how to make taskbar icon respond to left-click - python

Using wxPython, I created a taskbar icon and menu.
Everything works fine (in Windows at least) upon right-click of the icon: i.e., the menu is displayed, and automatically hidden when you click somewhere else, like on Windows' taskbar.
Now I do want to have the menu appear when the icon is left-clicked as well.
So I inserted a Bind() to a left-click in the Frame class wrapper, calling the CreatePopupMenu() of the taskbar icon:
import wx
class BibTaskBarIcon(wx.TaskBarIcon):
def __init__(self, frame):
wx.TaskBarIcon.__init__(self)
self.frame = frame
icon = wx.Icon('test_icon.ico', wx.BITMAP_TYPE_ICO)
self.SetIcon(icon, "title")
def CreatePopupMenu(self):
self.menu = wx.Menu()
self.menu.Append(wx.NewId(), "dummy menu ")
self.menu.Append(wx.NewId(), "dummy menu 2")
return self.menu
class TaskBarFrame(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, style=wx.FRAME_NO_TASKBAR)
...
self.tbicon = BibTaskBarIcon(self)
wx.EVT_TASKBAR_LEFT_UP(self.tbicon, self.OnTaskBarLeftClick)
...
def OnTaskBarLeftClick(self, evt):
self.PopupMenu(self.tbicon.CreatePopupMenu())
...
def main(argv=None):
app = wx.App(False)
TaskBarFrame(None, "testing frame")
app.MainLoop()
This works fine, except that the menu does not disappear automatically when you click somewhere else on your screen. In fact, left-clicking multiple times on the icon creates multiple menus. The only way to hide the menu(s) is to click on one of its items (which you don't always want). I've looked at the available methods of TaskbarIcon, but I failed to be clear about which one to use to hide the menu (.Destroy() didn't work). Moreover, I don't know which event to bind it to (there is a EVT_SET_FOCUS, but I couldn't find any EVT_LOOSE_FOCUS or similar).
So, how to hide the menu upon losing focus?
EDIT: I've inserted a bit more code, to make it more clear

Ah, I've discovered what went wrong. In the statement
self.PopupMenu(self.tbicon.CreatePopupMenu())
I had bound the popup menu to the frame, instead of to the taskbar icon.
By changing it to:
self.tbicon.PopupMenu(self.tbicon.CreatePopupMenu())
all is working well now.
Thanks for all remarks

I think the problem here is that the PopupMenu is usually used in a program's context, not a little icon in the system tray. What that means is that in a normal frame, the popup menu would detect the click the you clicked off of it. Here, you are clicking outside of the wxPython program. Also, the PopupMenu is usually used with EVT_CONTEXT_MENU, not this taskbar event.
You can try wx.EVT_KILL_FOCUS and see if that works since it should theoretically fire when you click off the menu. Or you could ask on the official wxPython forum here: http://groups.google.com/group/wxpython-users/topics
Mike Driscoll
Blog: http://blog.pythonlibrary.org

Related

How to sound a bell when the user clicks outside a modal window?

The situation is simple. I have a main window with a Help - About menu.
When this menu item is clicked, a modal window is opened (let's say it's an About-window).
With self.grab_set() I disabled the main-window (although the modal window does flicker when you click the main title bar).
So far, so good.
Here is the question: I really like to sound a bell when the user clicks outside the modal window on the main window.
This is what I could find about grab_set(), really not that much:
[effbot] ...a method called grab_set, which makes sure that no mouse or keyboard
events are sent to the wrong window.
[effbot] Routes all events for this application to this widget.
[kite.com] A grab directs all events to this and descendant widgets in the application.
[google books] grab_set() ensures that all of the application's events are sent to w until a corresponding call is made to grab_release ([Me:] or till the window is destroyed?)
I'm not quite sure how to understand this: does it mean you can handle an event on the main window within the modal window (like sounding my bell)?
So I tried things like:
self.bind('<Button-1>', self.bell) Exception in Tkinter callback: _tkinter.TclError: bad window path name
parent.bind('<Button-1>', self.bell) Nothing happens
So, how to sound a bell like when clicked outside the modal window on the main window, like in so many other applications?
Derived questions:
Is it still possible to cature events from the main window after using
grab_set for the modal window?
Is there a way to prevent the flickering?
I really like to understand this mysterious grab_set() method.
Stripped code:
import tkinter as tk
class About(tk.Toplevel):
def __init__(self, parent):
tk.Toplevel.__init__(self, parent)
self.geometry('200x150')
#--- OK button
btn_ok = tk.Button(self, text='OK', command=self.destroy) # destroy with OK
btn_ok.pack(side=tk.TOP)
btn_ok.focus() # destroy with spacebar
#--- Make window modal
self.grab_set()
# self.wait_window() # is this necessary in this case?
# self.bind('<Button-1>', self.bell) ??? The question
class MenuBar(tk.Menu):
def __init__(self, parent):
tk.Menu.__init__(self)
helpmenu = tk.Menu(self, tearoff=0)
helpmenu.add_command(label='About', command=lambda: About(parent))
self.add_cascade(label='Help', menu=helpmenu)
class MainApp():
def __init__(self, parent):
parent.configure(background='#000000')
parent.geometry('800x600')
menubar = MenuBar(parent)
parent.configure(menu=menubar)
if __name__ == '__main__':
root = tk.Tk()
MainApp(root)
root.mainloop()
When you set a grab, all button clicks will go to the window with the grab. You capture them the way you capture any other event. In the case of a button click you do that by binding a function to <1>.
It's important to know that a binding on a root window or a Toplevel window will apply to all widgets in that window. For example, binding to self in your code will fire even when you click on the "Ok" button. Therefore, the callback should probably only do work when the widget associated with the event is the same as the toplevel.
Example:
class About(tk.Toplevel):
def __init__(self, parent):
...
self.bind("<1>", self.capture_click)
...
def capture_click(self, event):
if event.widget == self:
<your logic here>
In the case of wanting to know if the user clicked outside the window, you can use the coordinates of the event object to compare against the window to see if the click is inside or outside.
def on_click(self, event):
if event.widget == self:
if (event.x < 0 or event.x > self.winfo_width() or
event.y < 0 or event.y > self.winfo_height()):
self.bell()
I found a second solution. Though my question was explicitly about using grab_set(), this method does the same for me: making the window as modal as possible and sound a bell.
Instead of using self.grab(), you can also disable the parent window:
parent.attributes('-disabled', True)
Of course it needs to be enabled again when the OK button is clicked (and when the windows is closed with the [X] close control. However, my original About-window has no window decoration). The command for the OK-button becomes:
btn_ok = tk.Button(self, text='OK', command=lambda: self.closeme(parent))
...which calls the closeme function:
def closeme(self, parent):
parent.attributes('-disabled', False)
self.destroy()
The bell sounds automatically when clicking a disabled window.
Method 1: Keeps you in full control of the main window but does not 'freeze' the main window: you can still move it around.
Method 2: Completely freezes the main window, but if it happens to be (partially) covered by another window (not of this application), then you can only bring back to top using Alt+Tab (windows).
I'm sure I will use both techniques in the future depending on my needs.

Tkinter: Window flash when attempting to click away

Ive been trying to do this for a while now, but haven't figured out a way to do it.
I have a tkinter script, that creates a popup window when a button is pressed. However I don't want the user to be able to click away from this window to any previous windows created. I have got this working with root.grab_set(), however there is no indication to the user that they must stay on that window.
class popup(object):
def __init__(self, parent):
self.root=Toplevel(parent)
self.root.grab_set() #prevents the user clicking on the parent window
#But the window doesnt 'flash' when an attempt to click away is made
For example, when you have a window created by the filedialogue module, if you attempt to click onto another window the filedialogue window stays on top and has a 'flashing' animation to let the user know they cant click away. Is there a way I can reproduce this effect? Going through the source of filedialogue hasn't been fruitful for me, and neither have Google searches.
The simplest way i can think to do this is to use an event and the focus commands, along with the windows bell command:
#!python3
import tkinter as tk
class popup(object):
def __init__(self, parent):
self.root=tk.Toplevel(parent)
self.root.title("Popup")
self.root.bind("<FocusOut>", self.Alarm)
def Alarm(self, event):
self.root.focus_force()
self.root.bell()
main = tk.Tk()
main.title("Main")
pop = popup(main)
main.mainloop()
Here's a solution for Windows that uses FlashWindowEx from the user32 dll. You need to pass a FLASHWINFO object to it. The grab_set makes sure the popup window stays in focus and disables any widgets in the main window, making the popup transient makes sure it's always on top of the master. The <Button-1> event is used to check mouse clicks, and winfo_containing checks if another window than the popup is clicked. I then set the focus back to the popup and flash the window in focus (which then always is the popup).
You need pywin32 to use this.
import Tkinter as tk
from ctypes import *
import win32con
class popup(object):
def __init__(self, parent):
self.parent = parent
self.root=tk.Toplevel(self.parent)
self.root.title("Popup")
self.root.grab_set()
self.root.transient(self.parent)
self.root.bind("<Button-1>", self.flash)
def flash(self, event):
if self.root.winfo_containing(event.x_root, event.y_root)!=self.root:
self.root.focus_set()
number_of_flashes = 5
flash_time = 80
info = FLASHWINFO(0,
windll.user32.GetForegroundWindow(),
win32con.FLASHW_ALL,
number_of_flashes,
flash_time)
info.cbSize = sizeof(info)
windll.user32.FlashWindowEx(byref(info))
class FLASHWINFO(Structure):
_fields_ = [('cbSize', c_uint),
('hwnd', c_uint),
('dwFlags', c_uint),
('uCount', c_uint),
('dwTimeout', c_uint)]
main = tk.Tk()
main.title("Main")
pop = popup(main)
main.mainloop()
As it is now, the flash only occurs when the main window's body is clicked, so clicking the title bar just returns the focus to the popup without flashing. To make it fire also when that happens you could try using the <FocusOut> event, but you would have to make sure it only happens when the focus passes to the main window, but it never really does since the grab_set is used. You might want to figure that out, but as it is now it works quite well. So it's not perfect, but I hope it helps.

tkinter menu accelerators and modal dialog boxes

I want to have a menu that shows a modal dialog box. Everything is fine, until I add an accelerator. If I do this and use the accelerator to access to dialog, it hangs. I suspect that wait_window, used inside the modal dialog box is somehow in conflict with the mainloop, when called from a "bind". Here is an example:
import tkinter
from tkinter import simpledialog
class App(tkinter.Tk):
def __init__(self):
tkinter.Tk.__init__(self)
self.bind_all("<Control-f>", lambda event: self.menu_file())
menubar = tkinter.Menu(self)
fileMenu = tkinter.Menu(menubar, tearoff=False)
fileMenu.add_command(label="File", underline=0,
command=self.menu_file, accelerator="Control+f")
# fileMenu.add_command(label="File", underline=0,
# command=self.menu_file)
menubar.add_cascade(label="File",underline=0, menu=fileMenu)
self.config(menu=menubar)
def menu_file(self):
simpledialog.Dialog(self,"Message")
app=App()
app.mainloop()
If in the above code I comment out the line that adds the accelerator and uncomment the subsequent line, there is no hangup (I can of course still use Ctrl+F to access the dialog box). The only problem is that the accelerator string is not shown next to the File menu. According to the tkinter documentations on the web that I have found, adding the accelerator should only change how the menu is shown and nothing else, so I am really puzzled. Anyone any ideas? (I could of course emulate accelerators by modifying the strings to be displayed, but I would not consider this as an elegant solution.)
As I have noticed, this is a Mac-specific bug.
Following the workaround suggested for a known Tk bug on Mac (see link), changing the line which binds the menu method to the keystroke to the following:
self.bind_all("<Command-f>", lambda event: self.after(100,self.menu_file))
is "fixing" the bug. They also suggest to increase 100 to 150 on slower systems. Hmm..

Cannot access text entry box after reopen the GTK window

First of all, this issue is only happened in WIN7, and it is normally under raspberry pi (Debian Linux).
I have two window, the main window and a child window. The main window has a button which can activate the child window. The child window has a text entry box which can input the strings. The issue is when activate the child window at 1st time, the text entry box is functional. But when the child window is closed and re-opened, the text entry box seems disabled that cannot input any text into it, even set_text("xx") function cannot write any text into it.
The detailed steps are:
run the py script
click the button on main window to open the child window. I have tried with the below three methods, it seems they have same issue:
def on_button_clicked(self, widget, data=None):
self.child_window.present()
#self.child_window.show()
#self.child_window.show_all()
Now the child window is opened and the text entry box is functional, I can type any text into it.
Close the child window. I have bind the delete signal on to the child window. So every time the child window is closed, the below function will be executed, which will hide the current child window.
def on_WindowOfScanning_delete_event(self, widget, data=None):
self.child_window.hide()
return True
Now the main window is on focus and click the button to activate the child window again.
self.child_window.present()
Now the child window is appear, but the text entry box seems disabled.
Any one can help me on this issue? Appreciated for that..
The version information is: Python 2.7.3 GTK 2.24.2, and I use glade to manage the GUI interface.
================= The same question with a different example: =====================
http://www.pygtk.org/pygtk2tutorial/sec-TextEntries.html#entryfig
This link is the pygtk's official example. While running on my WIN7(64bit) system, the text entry box cannot be edited since the first time opening. But if you move mouse to activate other window, and turn back to this gtk window, the text entry box can be edited then. I am not sure if this is a pygtk's bug.
I have tried python 2.6.6 and 2.7.3 with pygtk2.24.2-all-in-one.
================= The solution to this issue: =====================
It seems no one have such kind of problem so I post my own solution.
1st, give up using the window.hide() function.
2nd, destroy the child window every time it finished its job, and re-init the gtk.Window again to invoke the child window. Here is a simple example:
#!/usr/bin/env python
import pygtk
pygtk.require( "2.0" )
import gtk
class PopupExample(gtk.Window):
def __init__( self ):
gtk.Window.__init__(self)
self.connect("destroy", lambda *w: gtk.main_quit())
button = gtk.Button("Popup Window")
button.connect("clicked", self.show_popup_window)
self.add(button)
def show_popup_window(self, button):
popup = gtk.Window()
popup.add(gtk.Entry())
popup.show_all()
if __name__ == "__main__":
pe = PopupExample()
pe.show_all()
gtk.main()
I encountered the same problem in gnucash and inkscape,
I solved this problem by going into Control Panel -> Locales and Languages and set format to English(US)

How to pass along menu shortcuts from child widget holding focus in PyQt4?

I have a QMainWindow with a menu bar, including menu items for Save, Open and Quit with the usual shortcuts. It creates a QTableWidget that lists a bunch of different categories from which the user can choose (at his option).
If the user clicks into the QTableWidget to change categories, the widget takes the focus. That's mostly what I want, but unfortunately it also seems to steal the menu shortcuts, so that pressing Ctrl+S no longer triggers the save.
I experimented with keyPressEvent to solve this, but it seems like overkill even if I do get it working. Isn't there a way to delegate all the control/menu keys back to the QMainWindow ?
There must be an issue with how you are creating your QMenuBar. Here is an example that works just fine for me. The Save continues to function regardless of focus being in the table:
class Window(QtGui.QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.resize(640,480)
menuBar = self.menuBar()
menu = menuBar.addMenu("&File")
action = menu.addAction("&Save", self.doAction)
action.setShortcuts(QtGui.QKeySequence.Save)
self.view = QtGui.QTableWidget(5,5)
self.setCentralWidget(self.view)
def doAction(self):
print "Save"

Categories