I'm running tkinter in Python 3.4. A button event seems to remain bound to a command even after the application terminates. Code snippet:
# application class
class DataSel:
def __init__(self,parent):
self.parent = parent
<...>
self.button_sel = tk.Button(self.parent,text='Select')
self.button_sel.grid(row=1,sticky='nesw')
self.button_sel.bind('<Button-1>',self.sel_click)
self.button_quit = tk.Button(self.parent,text='Quit')
self.button_quit.grid(row=2,sticky='nesw')
self.button_quit.bind('<Button-1>',self.quit_click)
def sel_click(self,event):
self.filename = askopenfilename(parent=self.parent)
<...>
def quit_click(self,event):
self.parent.destroy()
# main part of application
root = tk.Tk()
root.lift()
sel = DataSel(root)
root.lift()
root.mainloop()
When I restart the interpreter from scratch and run this application, there is no error message. However, the button_sel button remains pressed (in low relief) after the sel_click method is finished. Then, if I quit the application and rerun it, I get the following message in the shell:
invalid command name ".94227256"
while executing
"$w cget -state"
(procedure "tk::ButtonDown" line 12)
invoked from within
"tk::ButtonDown .94227256"
(command bound to event)
where the number .94227256 changes each time I rerun.
Apart from this message, and the fact that the button remains in low relief, all other functionality is OK. But it seems like the button event somehow stays bound to a stale command!
What is happening is that your binding happens before the button widget is able to process the same event. You are doing this during the processing of the events and you aren't telling Tkinter to stop processing the events further. Therefore, when Tkinter gets around to having the widget process the click event, the window no longer exists and tkinter throws an error.
The root of the problem is that you are putting bindings on a button. You shouldn't do that. If you want to call a function from a button you need to use the command attribute of the button.
If you really think you need to do this via a binding (rather than via the command attribute), you need your function to return '"break"` to tell tkinter to stop any further processing of the event.
I know in Tkinter that the "<Configure>" event handles size changes in a window. However, I need to distinguish between when a user hits the maximize button, the restore button and when the user is resizing the window (instead of all three at once). Any ideas on how to do this? Is there a standard way? For instance, when a user hits maximize, I want to execute my code to maximize. When the user hits restore, I want to execute different code to restore. When the user drags to resize (or uses the keyboard shortcut to do so) I want it to execute different code altogether.
I can't think of a built-in way to track these events, but you could use the state() method on your root window to track changes. You can check the returned values of state(), specifically normal and zoomed (looks like Windows and OSX only), and call your own methods to handle the resize type based off those values. Here's a example to clarify:
class App(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
# initialize the new_state
self.new_state = 'normal'
self.parent.bind('<Configure>', self._resize_handler)
def _resize_handler(self, event):
self.old_state = self.new_state # assign the old state value
self.new_state = self.parent.state() # get the new state value
if self.new_state == 'zoomed':
print('maximize event')
elif self.new_state == 'normal' and self.old_state == 'zoomed':
print('restore event')
else:
print('dragged resize event')
root = Tk()
App(root).pack()
root.mainloop()
If you want to distinguish between dragging the window and dragging to resize, you'll have to add some extra checks, maybe storing the size before <Configure> and the size after, with winfo_height() and winfo_width(), and if no change occurs, you know the window was only repositioned.
Hope that helps.
I'm feeling somewhat like Python programming may not be my thing....
I have created a tkinter GUI that uses a button callback to open another window (other searches say this window should be a top-level window) and it works pretty good, how-ever each time the button is pressed it opens another identical (as far as I can tell) window.
Question: how can I test to see if a window (opened with the button) already exists and thus prevent duplicates from being generated???
NOTE: I am not (yet) a OOP programmer so please avoid that paradigm if possible...
regards,
Bill W.
I am not (yet) a OOP programmer so please avoid that paradigm if possible...
Sooner or later, you'll have to understand object-oriented programming if you want to program in Python successfully. The alternative (global variables and functions everywhere) is not definitely a good approach. Even Tkinter has lots of classes with its respective methods, so it looks like it is necessary for your purpose.
Back to your question, a solution could be setting the Toplevel window as an attribute of a class where you wrap all your application, and only open a new window if this attribute is None. To set this attribute to None when you close the window, you can use the protocol method to set a callback.
This is a small working example where you can see how it would work:
import Tkinter as tk
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.button = tk.Button(self, text="Open a new window", command=self.openwindow)
self.button.pack()
self.toplevel = None
def openwindow(self):
if self.toplevel is None:
self.toplevel = tk.Toplevel(self)
self.toplevel.protocol('WM_DELETE_WINDOW', self.removewindow)
def removewindow(self):
self.toplevel.destroy()
self.toplevel = None
app = App()
app.mainloop()
You can use this method winfo_exists() to check if the window exists.
if the return value is 0, it means the window doesn't exist.
if the return value is 1, it means the window exists.
Sample Code...
from tkinter import *
mainWindow = Tk()
mainWindow.title("This is main Window")
# create a top-level window
newWindow = Toplevel(mainWindow)
newWindow.title("This is Toplevel window")
print("Before destroying window = " + str(newWindow.winfo_exists()))
newWindow.destroy()
print("After destroying window = " + str(newWindow.winfo_exists()))
mainloop()
Output is...
# Before destroying window = 1
# After destroying window = 0
i'm hoping anyone can help me out here. i'm having an issue with a tkinter gui i built. the issue only happens in windows. My GUI creates a results frame with some labels in it, when it's time to calculate something else, the user clicks on the "newPort" button and that button is supposed to remove the results frame and set to False some instance attributes internal to the calculation. The issue i'm having, which is apparent only in windows is that sometimes the results frame, and its descendant labels don't disappear every time. Sometimes they do, sometimes they don't. The instance variable is correctly set to False but the widgets are still visible on the main GUI. The GUI also contains a couple checkboxes and radiobuttons but they don't impact the creation of the results frame nor its expected destruction. I have not been able to pin point a pattern of actions the user takes before clicking on the newPort button which causes the frame and labels to not get destroyed. This happens when i freeze my app with py2exe, as well as running the app from the python interpreter within the eclipse IDE. I have not tried running the app from the python interpreter directly (i.e. without the IDE) and this problem does not happen on my Mac when i run the app using the eclipse python interpreter. Thanks very much all! My code looks like this:
import Tkinter as TK
class widget(object):
def __init__(self,parent=None):
self.parent = TK.Frame(parent)
self.parent.grid()
self.frame = TK.Frame(self.parent)
self.frame.grid()
newLedger = TK.Button(self.parent,command=self.newPort).grid()
self.calcButton = TK.Button(self.frame,command=self.showResults)
self.calcButton.grid()
self.calcVariable = True
def newPort(self):
self.calcVariable = False
try:
self.second.grid_forget()
self.first.grid_forget()
self.resultsFrame.grid_forget()
self.second.destroy()
self.first.destroy()
self.resultsFrame.destroy()
except:
raise
self.frame.update_idletasks()
def showResults(self):
self.resultsFrame = TK.Frame(self.frame)
self.resultsFrame.grid()
self.first = TK.Label(self.resultsFrame,text='first')
self.first.grid()
self.second = TK.Label(self.resultsFrame,text='second')
self.second.grid()
if __name__ == '__main__':
root = TK.Tk()
obj = widget(root)
root.mainloop()
You don't need to destroy or call grid_forget on the labels, and you don't need to call grid_forget on the resultsFrame; when you destroy the resultsFrame it will cause all off its children to be destroyed, and when these widgets are destroyed they will no longer be managed by grid.
The only way I can get widgets to not be destroyed is if I click on the "calc" button twice in a row without clicking on the "new" button in-between. I'm doing this by running your program from the command line.
How do I get a Tkinter application to jump to the front? Currently, the window appears behind all my other windows and doesn't get focus.
Is there some method I should be calling?
Assuming you mean your application windows when you say "my other windows", you can use the lift() method on a Toplevel or Tk:
root.lift()
If you want the window to stay above all other windows, use:
root.attributes("-topmost", True)
Where root is your Toplevel or Tk. Don't forget the - infront of "topmost"!
To make it temporary, disable topmost right after:
def raise_above_all(window):
window.attributes('-topmost', 1)
window.attributes('-topmost', 0)
Just pass in the window you want to raise as a argument, and this should work.
Add the following lines before the mainloop():
root.lift()
root.attributes('-topmost',True)
root.after_idle(root.attributes,'-topmost',False)
It works perfectly for me. It makes the window come to the front when the window is generated, and it won't keep it always be in the front.
If you're doing this on a Mac, use AppleEvents to give focus to Python. Eg:
import os
os.system('''/usr/bin/osascript -e 'tell app "Finder" to set frontmost of process "Python" to true' ''')
Regarding the Mac, I noticed there can be a problem in that if there are multiple python GUIs running, every process will be named "Python" and AppleScript will tend to promote the wrong one to the front. Here's my solution. The idea is to grab a list of running process IDs before and after you load Tkinter. (Note that these are AppleScript process IDs which seem to bear no relation to their posix counterparts. Go figure.) Then the odd man out will be yours and you move that one to frontmost. (I didn't think that loop at the end would be necessary, but if you simply get every process whose ID is procID, AppleScript apparently returns the one object identified by name, which of course is that non-unique "Python", so we are back to square one unless there's something I'm missing.)
import Tkinter, subprocess
def applescript(script):
return subprocess.check_output(['/usr/bin/osascript', '-e', script])
def procidset():
return set(applescript(
'tell app "System Events" to return id of every process whose name is "Python"'
).replace(',','').split())
idset = procidset()
root = Tkinter.Tk()
procid = iter(procidset() - idset).next()
applescript('''
tell app "System Events"
repeat with proc in every process whose name is "Python"
if id of proc is ''' + procid + ''' then
set frontmost of proc to true
exit repeat
end if
end repeat
end tell''')
On Mac OS X PyObjC provides a cleaner and less error prone method than shelling out to osascript:
import os
from Cocoa import NSRunningApplication, NSApplicationActivateIgnoringOtherApps
app = NSRunningApplication.runningApplicationWithProcessIdentifier_(os.getpid())
app.activateWithOptions_(NSApplicationActivateIgnoringOtherApps)
Recently, I had the same question on the Mac. I have combined several answers using #MagerValp for the Mac and #D K for other systems:
import platform
if platform.system() != 'Darwin':
root.lift()
root.call('wm', 'attributes', '.', '-topmost', True)
root.after_idle(root.call, 'wm', 'attributes', '.', '-topmost', False)
else:
import os
from Cocoa import NSRunningApplication, NSApplicationActivateIgnoringOtherApps
app = NSRunningApplication.runningApplicationWithProcessIdentifier_(os.getpid())
app.activateWithOptions_(NSApplicationActivateIgnoringOtherApps)
root.mainloop()
Somewhat of a combination of various other methods, this works on OS X 10.11, and Python 3.5.1 running in a venv, and should work on other platforms too. It also targets the app by process id rather than app name.
from tkinter import Tk
import os
import subprocess
import platform
def raise_app(root: Tk):
root.attributes("-topmost", True)
if platform.system() == 'Darwin':
tmpl = 'tell application "System Events" to set frontmost of every process whose unix id is {} to true'
script = tmpl.format(os.getpid())
output = subprocess.check_call(['/usr/bin/osascript', '-e', script])
root.after(0, lambda: root.attributes("-topmost", False))
You call it right before the mainloop() call, like so:
raise_app(root)
root.mainloop()
There's a hint on how to make the Tkinter window take focus when you call mainloop() in the Tkinter._test() function.
# The following three commands are needed so the window pops
# up on top on Windows...
root.iconify()
root.update()
root.deiconify()
root.mainloop()
This is the cleanest most proper way I've found to do this, but it's only needed for Windows systems.
This answer is to make one Tkinter Window pop up overtop of other Tkinter windows.
In my app I have a large window toplevel which calls a much smaller window top2 which initially appears on top of toplevel.
If user clicks within toplevel window it gains focus and smothers much smaller top2 window until toplevel window is dragged off of it.
The solution is to click the button in toplevel to launch top2 again. The top2 open function knows it is already running so simply lifts it to the top and gives it focus:
def play_items(self):
''' Play 1 or more songs in listbox.selection(). Define buttons:
Close, Pause, Prev, Next, Commercial and Intermission
'''
if self.top2_is_active is True:
self.top2.focus_force() # Get focus
self.top2.lift() # Raise in stacking order
root.update()
return # Don't want to start playing again
On macOS High Sierra, py3.6.4, here is my solution:
def OnFocusIn(event):
if type(event.widget).__name__ == 'Tk':
event.widget.attributes('-topmost', False)
# Create and configure your root ...
root.attributes('-topmost', True)
root.focus_force()
root.bind('<FocusIn>', OnFocusIn)
The idea is to bring it to the front until user interacts with it, i.e., taking focus.
I tried the accepted answer, .after_idle(), and .after(). They all fail in one case: When I run my script directly from an IDE like PyCharm, the app window will stay behind.
My solution works in all the cases that I encountered.
One more line (needed for Python 3.11 and tkinter 8.6):
def lift_window(window):
window.attributes('-topmost', True)
window.update_idletasks() # get window on top
window.attributes('-topmost', False) # prevent permanent focus
window.focus_force() # focus to the window
This will lift the window to the front, and also focus on the window.
def lift_window(window):
window.attributes('-topmost',True)
window.attributes('-topmost',False) # disable the topmost attribute after it is at the front to prevent permanent focus
window.focus_force() # focus to the window