代码之家  ›  专栏  ›  技术社区  ›  d-cubed Tyler Rinker

如何使用python tksimpledialog.askstring

  •  3
  • d-cubed Tyler Rinker  · 技术社区  · 16 年前

    我想使用askstring提示的响应来设置变量。不幸的是, 我有一个两难的处境,我陷入了一个循环,询问问题,或者窗口拒绝绘制,因为变量(urltoopen)没有值。 代码如下:

    urltoopen = tkSimpleDialog.askstring('Address', 'Where do we get the pictures from?')
    usock = urllib2.urlopen(urltoopen)
    data = usock.read()    
    usock.close()                     
    
    2 回复  |  直到 16 年前
        1
  •  3
  •   Alex Martelli    16 年前

    tkSimpleDialog.askstring 收益率 None 如果用户单击“取消”或关闭窗口(而不是单击“确定”或使用Enter键);您应该检查(如果用户选择取消,您想做什么?当然不叫 urlopen 总之……)

    除此之外,您正确地使用了函数;我认为“没有值”是指 is None 对吧?

        2
  •  0
  •   d-cubed Tyler Rinker    16 年前
    
    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()    
    

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