变量和函数

2024-03-28 17:44:35 发布

您现在位置:Python中文网/ 问答频道 /正文

基本上,我正在尝试构建一个Tkinter窗口,它接受4个值,并在一个新标签中打印由函数P_n(s,n,v,h)计算的结果

我就是不能让它工作。这是密码。你知道吗

from Tkinter import *

def binomialco(p,k):
  Sum = 1
  Pro = 1
  for i in range(0,k):
      Sum = Sum*(p-i)
  for i in range(1,k+1):
      Pro = Pro*i
  return float(Sum)/float(Pro)


def B(s,n,v,h):
  arithmitis = binomialco(n-1,s)*(v*h)**s
  paronomastis = 0
  for i in range(0,s+1):
      d= binomialco(n-1,i+1)*(v*h)**i
      paronomastis+=d
  B=arithmitis/paronomastis
  return B

def P0(s,n,v,h):
  athroisma = 0
  for i in range(0,s+1):
      dent= binomialco(n-1,i)*(v*h)**i
      athroisma+=dent
  athroisma = athroisma**(-1)
  return "{:.2%}".format(athroisma)

def P_n(s,n,v,h):
  paragodas_1=binomialco(n-1,s)
  athroisma_2=paragodas_1*((v*h)**s)*P0(s,n,v,h)
  var.set("{:.2%}".format(athroisma_2))
  print var



def B_2(s,n,v,h):
  pano=(n-s)*v*h*P_n(s-1,n,v,h)
  kato= s+pano
  return pano/kato


root=Tk()

label_1=Label(root,text="Type value for s:")
label_2=Label(root,text="Type value for n:")
label_3=Label(root,text="Type value for v:")
label_4=Label(root,text="Type value for h:")


entry_1=Entry(root)
entry_2=Entry(root)
entry_3=Entry(root)
entry_4=Entry(root)


button_1=Button(root,text="Calculate",command= lambda: P_n(int(entry_1.get()),int(entry_2.get()),float(entry_3.get()),float(entry_4.get())))


label_1.grid(row=0)
label_2.grid(row=1)
label_3.grid(row=2)
label_4.grid(row=3)

entry_1.grid(row=0,column=1)
entry_2.grid(row=1,column=1)
entry_3.grid(row=2,column=1)
entry_4.grid(row=3,column=1)
button_1.grid(row=4,columnspan=2)


root.mainloop()

这是错误:

Exception in Tkinter callback
Traceback (most recent call last):
File      "    /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1486, in __call__
return self.func(*args)
File "/Users/harrytou/Desktop/nikoskaievita.py", line 58, in <lambda>
button_1=Button(root,text="Calculate",command= lambda:   P_n(int(entry_1.get()),int(entry_2.get()),float(entry_3.get()),float(entry_  4.get())))
File "/Users/harrytou/Desktop/nikoskaievita.py", line 32, in P_n
athroisma_2=paragodas_1*((v*h)**s)*P0(s,n,v,h)
TypeError: can't multiply sequence by non-int of type 'float'

我给出的值是2,4,0.03333,3。结果应为2.26%。你知道吗


Tags: textinforgetreturndefrootfloat
1条回答
网友
1楼 · 发布于 2024-03-28 17:44:35

您提到的具体问题是由于P0返回的字符串类似于"7.69%"。然后尝试在失败的计算中使用该值。当错误消息说“不能相乘序列…”时,这个字符串就是它所指的:这个字符串就是序列,显然你不能像现在这样在计算中使用字符串。(您还有一个问题,在调用var.set(...)之前没有定义var,但这是一个单独的问题)。你知道吗

这个问题很容易找到,我只是在做最后的计算之前把P_n中的所有值都打印出来。这应该是您调试此问题的第一步。你知道吗

这里还有一些建议:如果不使用lambda的方式,代码将更易于调试、理解和维护。让按钮调用一个适当的函数,并让函数在进行计算之前获取值。你知道吗

def do_calculation():
    e1 = int(entry_1.get())
    e2 = int(entry_2.get())
    e3 = float(entry_3.get())
    e4 = float(entry_4.get())

    P_n(e1,e2,e3,e4)

...
button_1=Button(..., command= do_calculation)
...

相关问题 更多 >