簡體   English   中英

如何將 tkinter 條目轉換為整數

[英]How do you convert a tkinter entry to an integer

我需要在等式中使用 GUI 中的條目,並且在嘗試將其轉換為整數時總是出現錯誤。 我試圖轉換的變量被標記為“半徑”。

import math
import tkinter as tk

circ = tk.Tk()
circ.title("Circle")
circ.geometry("150x75")

radiusLabel = tk.Label(circ, text = "What is the radius?")
radiusEntry = tk.Entry(circ)

def close_window():
    circ.destroy()

radius = int(radiusEntry)

submit = tk.Button(circ, text = "Submit", command = close_window)

radiusLabel.pack()
radiusEntry.pack()
submit.pack()
circ.mainloop()

class Shape():
    def __init__(self, radius):
        self.circumference = float(2) * float(radius) * float(math.pi)
        self.area = float(math.pi) * float(radius*radius)

    def getArea(self):
        return self.area

    def getPerimeter(self):
        return self.circumference

    def __str__(self):
        return "Area: %s, Circumference: %s" % (self.area, self.circumference)

circle = Shape(radius)
print(circle)

你可以試試這個功能,它對我有用

def cvtInt(value):
    fnum = []
    newnum = ''
    for i in value:
        ii = int(i)
        fnum.append(ii)
    for i in fnum:
        newnum = newnum + str(i)
    new = int(newnum)
    return new

可以幫助您解決此問題的三件事:

  1. 一般提示:在調試此類事情時,請使用打印語句查看是否獲得了預期的信息。 radiusEntry 總是給你一個數字嗎? 我的猜測可能不是。

  2. 我相信你應該使用radius = int(radiusEntry.get())來獲取輸入值

  3. 可能最好的辦法是在將半徑轉換為 ​​int 之前執行檢查,並確保您實際上是在嘗試轉換數字。 如果您嘗試轉換字母或 None 數據類型,這可能會導致您的錯誤。 您可以使用字符串的 python isnumeric()方法檢查這一點。

給你的偽代碼:

If the radius entry is a number,

   convert the radius entry to an int

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM