是個新人,今天是用python第二天,希望能找到幫助
import math
import tkinter as tk
window = tk.Tk()
window.title('測量坐標轉換')
window.geometry('200x100')
l1 = tk.Label(window,text='輸入極坐標',bg='yellow',font=('Arail',10),width = 10,height=2)
l1.place(x=10,y=20)
e1 = tk.Entry(window,font=('Arail',10),width=8,show=None)
e1.place(x=90,y=3)
e2 = tk.Entry(window,font=('Arail',10),width=8,show=None)
e2.place(x=90,y=40)
l2 = tk.Label(window,text='輸入直角坐標',bg='blue',font=('Arail',10),fg='white',width = 10,height=2)
l2.place(x=10,y=100)
e3 = tk.Entry(window,font=('Arail',10),width=8,show=None)
e3.place(x=90,y=90)
e4 = tk.Entry(window,font=('Arail',10),width=8,show=None)
e4.place(x=90,y=127)
l3 = tk.Label(window,text='轉換結果',bg='white',font=('Arail',10),width = 8,height=2)
l3.place(x=40,y=180)
t = tk.Text(window,width=8,height=1)
t.place(x=120,y=190)
def jtranslate():
a = e1.get()
b = (math.pi/180)*e2.get()
x = a*math.cos(b)
y = a*math.sin(b)
t.insert('top',x,y)
def ztranslate():
c = e3.get()
d = e4.get()
p = math.sqrt(c*c+d*d)
o = math.degrees(math.atan(c/d))
t.insert('top',p,o)
b1 = tk.Button(window,text='極坐標轉直角坐標',width=20,height=2,bg='yellow',command = jtranslate())
b1.place(x=170,y=10)
b2 = tk.Button(window,text='直角坐標轉極坐標',width=20,height=2,bg='blue',fg='white',command = ztranslate())
b2.place(x=170,y=97)
window.mainloop()
運行后的錯誤如下
Traceback (most recent call last):
File "D:/python/translate.py", line 35, in <module>
b1 = tk.Button(window,text='極坐標轉直角坐標',width=20,height=2,bg='yellow',command = jtranslate())
File "D:/python/translate.py", line 25, in jtranslate
b = (math.pi/180)*e2.get()
TypeError: can't multiply sequence by non-int of type 'float'
uj5u.com熱心網友回復:
試一下:b = (math.pi/180)*int(e2.get())從輸入框獲得的內容要轉成整數型。如果怕輸入的不是整數,還可以錯誤處理
uj5u.com熱心網友回復:
下面的一行也要改c和d的值也要轉為整數
uj5u.com熱心網友回復:
command = jtranslate() -->command = jtranslatecommand = ztranslate()-->command = ztranslate
uj5u.com熱心網友回復:
對于:b = (math.pi/180)*e2.get()
報錯:
TypeError: can't multiply sequence by non-int of type 'float'
上網(用google)搜找到
Python : TypeError: can't multiply sequence by non-int of type 'float' - Stack Overflow
等帖子。不過最后發現是:
看到另外人提到的,需要型別轉換,才意識到:
估計你此處是把輸入的字串直接當數字處理了
所以去看你代碼 e2的是來自
e2 = tk.Entry(window,font=('Arail',10),width=8,show=None)搜了下
python tk.Entry
找到
Python Tkinter 文本框(Entry) | 菜鳥教程
Python Tkinter 文本框用來讓用戶輸入一行文本字串。
-》很明顯,此處只是一個控制元件
-》所以get()得到的,肯定是,一個字串了
-》你可以加上列印型別的代碼
即,把
b = (math.pi/180)*e2.get()
改為
userInput = e2.get()
print("type(userInput)=%s" % type(userInput))
肯定輸出是:<class str>
意思是,你得到用戶輸入的值,看起來是數字的值,其實是字串
舉例:用戶輸入了 3
其實是 '3' 這個字串
而不是 3 這個整數數字
所以,解決辦法是,把輸入的(確定是數字類的)字串,轉換為整數(或浮點數):
userInput = e2.get()
print("type(userInput)=%s" % type(userInput))
userInputInt = int(userInput)
# userInputFloat = float(userInput)
然后再去和你的其他(float型別的)值去 相乘于
b = (math.pi/180) * userInputInt
# b = (math.pi/180) * userInputFloat
即可,就不會報錯了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/54165.html
上一篇:為什么爬蟲有的網站可以soup.find('div',class_= '2000' ). find,有的不可以,內置圖片求解惑
