Reputation: 345
I was trying out a python code example at Rosetta Code - a programming chrestomathy site, where solutions to the same task are presented in as many different programming languages as possible. For this task, the goal is to input a string and the integer 75000, from graphical user interface. The code is shown below:
import tkSimpleDialog
number = tkSimpleDialog.askinteger("Integer", "Enter a Number")
string = tkSimpleDialog.askstring("String", "Enter a String")
However, when I try to run the code, I get the following error:
Traceback (most recent call last):
File "C:\Users\vix\Documents\.cache\GUIexample.py", line 3, in <module>
number = tkSimpleDialog.askinteger("Integer", "Enter a Number")
File "C:\Python27\lib\lib-tk\tkSimpleDialog.py", line 262, in askinteger
d = _QueryInteger(title, prompt, **kw)
File "C:\Python27\lib\lib-tk\tkSimpleDialog.py", line 189, in __init__
Dialog.__init__(self, parent, title)
File "C:\Python27\lib\lib-tk\tkSimpleDialog.py", line 53, in __init__
if parent.winfo_viewable():
AttributeError: 'NoneType' object has no attribute 'winfo_viewable'
Where could the problem be?
Thanks
Upvotes: 11
Views: 10907
Reputation: 176760
The error message is telling you that the dialog needs a parent window.
With Python 2.x, you create the root window with:
import tkinter
from tkinter import simpledialog
root = tkinter.Tk()
To hide the root window if you don't want it, use:
root.withdraw()
See the Python Tkinter Docs for more info.
Upvotes: 20
Reputation: 385910
I've never used askinteger
, but judging from the error message it looks like the dialog needs to know its parent but you're not telling it what its parent should be. Try adding parent=widget
(where "widget" is a reference to some other widget -- typically the root widget). I can't find any documentation that says this is required, but I'm guessing it is since all Tkinter widgets except the root window need to have a parent.
If the code you show in your question is the complete code, you're missing some other things. You need to create an instance of the Tk
class (called the "root" window), and you need to start the event loop (though, it's possible that the dialog runs it's own event loop, so you might be OK if all you need is the single dialog).
Upvotes: 1