I have this function inside one of my python scripts which throws up a Tkinter simple dialog screen to ask for some simple user-input. The function works. However, there are 2 problems with it.
AttributeError: 'NoneType' object has no attribute 'winfo_viewable'
It would be nice to at one point figure that one out, but my main problem however is the second one:
Any help would be greatly appreciated!
My code:
def getUser():
master = Tk()
newList2=str(newList).replace(", ","\n")
for ch in ['[',']',"'"]:
if ch in newList2:
newList5=newList2.replace(ch,"")
userNr=simpledialog.askinteger("Enter user number", newList2)
chosenUsernr= userNr - 1
global chosenUsernrdef
chosenUsernrdef = chosenUsernr
master.destroy()
First, credits to Lafexlos for showing a solution of how to apply .lift()
and similar commands on a Tkinter simpledialog.askinteger() window by recreating such a window as a Tk() instance.
For those however looking how to automatically activate a Tk-window (so you do not have to click on it before being able to type in it), there appear to be multiple options.
The most common solution seems to be to use .focus()
or .force_focus()
as seen implemented here and here. However over here it seems those options may not work on (at least some versions of) Windows OS. This question shows a possible solution for those systems. Also, the previous solutions appear not to work on multiple versions of OS X. Based on the solution offered here, using Apple's osascript, I was able to solve my problem.
The working code eventually looks like this:
def getUser():
master = Tk()
newList2=str(newList).replace(", ","\n")
for ch in ['[',']',"'"]:
if ch in newList2:
newList2=newList2.replace(ch,"")
cmd = """osascript -e 'tell app "Finder" to set frontmost of process "Python" to true'"""
def stupidtrick():
os.system(cmd)
master.withdraw()
userNr=simpledialog.askinteger("Enter user number", newList2)
global chosenUsernrdef
chosenUsernr= userNr - 1
chosenUsernrdef = chosenUsernr
stupidtrick()
master.destroy()
Simplified / general solution:
import os
from tkinter import Tk
from tkinter import simpledialog
def get_user():
root = Tk()
cmd = """osascript -e 'tell app "Finder" to set frontmost of process "Python" to true'"""
def stupid_trick():
os.system(cmd)
root.withdraw()
new_window=simpledialog.askinteger("Title of window", "Text to show above entry field")
stupid_trick()
root.destroy()
get_user()
EDIT: Now I am figuring out what to look for the solution appears to be found already by multiple posts. For those on OS X wanting to activate a specific Tkinter window when multiple instances of Tkinter and/or python are running simultaneously, you might want to look here.