如果 > 到我在文本框中插入的數字,我想獲得數字 (B = 2 2) 的“Ok”列印。
第一個數字是
A = 2 2
A = Entry (root, width = 4, highlightthickness = 0, bg = "# ffffc0")
A.place (x = 1, y = 1)
if B > A:
print ("Ok")
我明白了TypeError: '>' not supported between instances of 'float'
我該如何解決?
uj5u.com熱心網友回復:
呼叫Entry()回傳一個物件,該物件是一個文本小部件并存盤在number2. 要獲取其內容,您需要呼叫其get()方法。結果將是型別str。
您將需要呼叫int(number2.get())或float(number2.get())獲取一個型別與問題中顯示的變數兼容的變數number1。
uj5u.com熱心網友回復:
您無法將Entry小部件與float變數進行比較。
參考檔案,了解更多。
因此,將Entry小textvariable部件的資料StringVar(doubleDoubleVarfloatint
因此,考慮到在 Entry 框中輸入的數字和 number1 都是整數值(也可以是大整數,帶有逗號)。我會將數字存盤為strings。(如果值是小數,請使用float而不是int。)
為了比較存盤在字串中的數字,我將創建一個函式valueOf來獲取這些字串的值作為 int 并洗掉逗號。
這個片段會給你一個想法:
from tkinter import *
window = Tk()
number2 = StringVar() #take the input number2 as a string (so that commas are also included)
entry_1 = Entry(window,textvariable=number2) #assign number2 as textvariable of this Entry box.
entry_1.place(x = 1, y = 1)
def valueOf(s):
if type(s) == str :
s = s.replace(',', '') #removes the commas from the number
if s=="" : #in case nothing was given in Entry box, consider it as 0
return 0
return int(s) #return the integer form of that number
def Compare():
#number1 = "2,552,555" #make sure to take this number as a string if commas are there
number1= 2 2 #this is already in int form
if valueOf(number1) > valueOf(number2.get()):
print ("Ok")
else:
print("Input is Equal or Greater")
button1 = Button(window, text="Print", command=Compare)
button1.place(x = 45, y = 30)
window.mainloop()
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/441036.html
標籤:Python python-3.x 细绳 tkinter 浮点
