11

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

4

2 回答 2

19

错误消息告诉您该对话框需要一个父窗口。

使用 Python 2.x,您可以使用以下命令创建根窗口:

import tkinter
from tkinter import simpledialog
root = tkinter.Tk()

如果您不想隐藏根窗口,请使用:

root.withdraw()

有关更多信息,请参阅Python Tkinter 文档

于 2012-04-18T14:08:36.703 回答
1

我从来没有使用过askinteger,但从错误消息来看,看起来对话框需要知道它的父级,但你并没有告诉它它的父级应该是什么。尝试添加parent=widget(其中“小部件”是对其他小部件的引用——通常是根小部件)。我找不到任何说明这是必需的文档,但我猜这是因为除了根窗口之外的所有 Tkinter 小部件都需要有一个父级。

如果您在问题中显示的代码是完整的代码,那么您会遗漏一些其他内容。您需要创建Tk该类的一个实例(称为“根”窗口),并且您需要启动事件循环(不过,对话框可能会运行它自己的事件循环,所以如果您需要的只是单个对话框)。

于 2012-04-18T10:47:25.103 回答