【问题标题】:Python 2.7 Tkinter variable type incompatibilityPython 2.7 Tkinter 变量类型不兼容
【发布时间】:2015-12-09 00:34:51
【问题描述】:

我试图将输入窗口中的值用作数值,但它不允许我根据程序(即使我只是输入数字)将“字符串”转换为浮点值。

简短示例:

输入来自:

etiquette5=Label(eqGroup,text="Insert value for c")
etiquette5.pack(padx=10,pady=5,expand=True,fill=BOTH)
input3=Entry(eqGroup,width=10)
input3.pack()

inputList[0]=input1.get() #To be able to move the inputs from this method I put them into a global list

输入用于:

def equationSolver(self): #For doing the math shenanigans
    a=float(inputList[0])#Error here. It is unable to convert the strings that it takes in via the input to float values
    b=float(inputList[1])#Error here. It is unable to convert the strings that it takes in via the input to float values
    c=float(inputList[2])#Error here. It is unable to convert the strings that it takes in via the input to float values

    X1=(-b/2)+(sqrt(pow(b/2,2)-c))
    X2=(-b/2)-(sqrt(pow(b/2,2)-c))

    globalList[0]=X1 #Once again, putting them into a global list for movement purposes
    globalList[1]=X2

错误图片

你可以在这里找到完整的代码:http://pastebin.com/1Umug0ms

关于如何做到这一点的任何想法?

提前致谢,斯塔根

【问题讨论】:

  • 您是否进行了任何调试以验证 inputList[0] 是您认为的那样?
  • 嗯,不。我不知道如何验证(我们从未在课堂上运行过调试会话)。但起初该值以 0 开头(您可以在完整脚本的顶部看到它)。所以它是一个整数,但后来它从输入变成了一个字符串(看起来)。至少发生了什么?
  • 您可以在equationSolver 中临时添加一条打印语句来打印出inputList 中的内容。我没有看到条目被初始化为零的任何地方。
  • 第 8 行和第 9 行。 globalList=[0,1,2,3] #全局列表,以便我可以在方法之间移动内容 inputList=[0,1,2,3,4,5,6 ]

标签: python-2.7 tkinter


【解决方案1】:

您在用户实际输入数据之前定义inputList。考虑这行代码:

inputList[0]=input1.get() 

这会将inputList[0] 设置为条目小部件中的值当时。如果这是在初始化函数中完成的(any 在显示 UI 之前调用的函数),则该值将为空。当您稍后尝试使用它时,您会收到一个错误,因为空字符串不是有效数字。

您需要延迟获取这些值,直到您准备好使用它们。

【讨论】:

  • 完整代码仍在此处:pastebin.com/1Umug0ms 但我确实先定义了列表,以确保它们成为全球性的,以便我可以随时访问它们。但是,对 inputList[0] 的调用不在 init 方法中。它是类中的几种方法。
  • 好的,你已经确认了我写的内容。在用户有机会输入任何数据之前,您正在重置 inputList(它不在 __init__ 方法中,但您仍在初始化期间设置变量。用户不会在您致电input1.get() 时,您已经有机会输入任何数据。
  • 但是如果我从顶部删除它,那么它说当我第一次尝试使用它时没有定义列表?它的全部意义在于尽早对其进行初始化,以便能够在方法之间移动它。我能以某种方式解决这个问题吗?因为我需要将 X1 和 X2 的答案移动到另一种方法,将它们作为答案写出来......
  • @Staggen:这些是无法在评论中回答的更深层次的问题。 Stackoverflow 不是一个讨论论坛。它是为人们提出一个问题,然后得到该问题的答案而设计的。它不是为长时间讨论而设计的。
猜你喜欢
  • 1970-01-01
  • 2012-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-11
  • 1970-01-01
  • 1970-01-01
  • 2019-11-08
相关资源
最近更新 更多