如何使用 Python tkSimpleDialog.askstring

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2003504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 23:32:10  来源:igfitidea点击:

How to use Python tkSimpleDialog.askstring

pythonuser-inputtkinter

提问by d-cubed

I want to use the response from an askstring prompt to set a variable. Unfortunately, I have the dilemma that I'm trapped in the loop asking the question or the window refuses to draw because the variable (urltoopen) has no value. The code as it stands:

我想使用来自 askstring 提示的响应来设置变量。不幸的是,我遇到了困境,我被困在问问题的循环中,或者窗口拒绝绘制,因为变量 (urltoopen) 没有值。代码如下:

urltoopen = tkSimpleDialog.askstring('Address', 'Where do we get the pictures from?')
usock = urllib2.urlopen(urltoopen)
data = usock.read()    
usock.close()                     

采纳答案by Alex Martelli

tkSimpleDialog.askstringreturns Noneif the user clicks Cancel or closes the window (instead of clicking Ok or using the Enter key); you should check for that (what do you want to do if the user chooses to cancel? surely not call urlopenanyway...).

None如果用户单击取消或关闭窗口(而不是单击确定或使用 Enter 键),则tkSimpleDialog.askstring返回;你应该检查一下(如果用户选择取消,你想做什么?当然不要打电话urlopen......)。

Apart from that, you're using the function correctly; I imagine that by "has no value" you mean is None, right?

除此之外,您正确使用了该功能;我想你的意思是“没有价值” is None,对吧?

回答by d-cubed


root = Tk()   


try:
        urltoopen = tkSimpleDialog.askstring('Ask Address', 'Where do we get the pictures from?')
        usock = urllib2.urlopen(urltoopen)                                                       
        data = usock.read()                                                                      
        usock.close()                                                                            
        a = data                                                                                 
except:                                                                                          
        sys.exit()    

works fine. But it does need error handling (as mentioned by Alex).

工作正常。但它确实需要错误处理(正如 Alex 所提到的)。