2012-04-18 104 views
8

我在Rosetta Code - programming chrestomathy網站嘗試了一個python代碼示例,其中儘可能多的不同編程語言提供了對同一任務的解決方案。對於這個任務,目標是從圖形用戶界面輸入一個字符串和整數75000。代碼如下所示:最小tkSimpleDialog示例中的錯誤

import tkSimpleDialog 

number = tkSimpleDialog.askinteger("Integer", "Enter a Number") 
string = tkSimpleDialog.askstring("String", "Enter a String") 

然而,當我嘗試運行的代碼,我得到以下錯誤:

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' 

可能在哪裏這個問題呢?

感謝

+0

發佈完整的追溯,而不僅僅是錯誤。我們需要查看錯誤代碼。 – agf 2012-04-18 08:02:53

+0

@agf我編輯了問題以包含回溯。 – engineervix 2012-04-18 08:16:24

+0

我在Windows 7 Ultimate 32位上使用Python 2.7。 'root = Tkinter.tk()'不起作用,它給出'NameError:name''Tkinter'沒有被定義' – engineervix 2012-04-18 08:28:37

回答

12

錯誤消息告訴您該對話框需要父窗口。

使用Python 2.x中,您創建了根窗口:

import Tkinter 
root = Tkinter.Tk() 

要隱藏根窗口,如果你不想要它,使用:

root.withdraw() 

Python Tkinter Docs爲更多信息。

+0

* T * k代替tk ...順便說一句。 – FabienAndre 2012-04-18 14:17:28

+0

@FabienAndre謝謝,修正。 – agf 2012-04-18 14:19:22

1

我從來沒有用過askinteger,但它看起來像對話框需要知道其父的錯誤信息判斷,但你不告訴它的父應該是什麼。嘗試添加parent=widget(其中「小部件」是對其他小部件的引用 - 通常是根小部件)。我找不到任何說明這是必需的文檔,但我猜測它是因爲除了根窗口以外的所有Tkinter窗口小部件都需要有父窗口。

如果您在問題中顯示的代碼是完整的代碼,那麼您錯過了其他一些內容。您需要創建一個Tk類的實例(稱爲「根」窗口),並且您需要啓動事件循環(儘管可能會由對話框運行它自己的事件循環,所以如果您需要的話您可能會確定是單個對話框)。