Skip to main content
 首页 » 编程设计

python之如何在 tkinter 中输入 int

2024年11月01日8webabcd

我想创建一个圆形计算器区域,因为我有一些空闲时间所以我尝试先在终端中运行它并且它可以工作但是当我决定添加一个小的 GUI 时我得到了一个错误 我的代码是这样的

from tkinter import * 
screen = Tk() 
screen.title("Area of Circle Calculator") 
screen.geometry("500x500") 
def submit(): 
    global done 
    pi = 3.14159265359 
    an = int(pi * radius*radius) 
    laod = Label(screen, text = "Hello" % (an)) 
    load.grid() 
ask = Label(screen, text = "What is the radius of the circle?") 
ask.pack() 
radius = Entry(screen) 
radius.pack() 
done = Button(screen, text="submit", command = submit) 
done.pack() 
screen.mainloop() 

这是我得到的错误

C:\Users\Timothy\Desktop>python aoc.py 
Exception in Tkinter callback 
Traceback (most recent call last): 
  File "C:\Users\Timothy\AppData\Local\Programs\Python\Python37-32\lib\tkinter\_ 
_init__.py", line 1705, in __call__ 
    return self.func(*args) 
  File "aoc.py", line 8, in submit 
    an = int(pi * radius*radius) 
TypeError: unsupported operand type(s) for *: 'float' and 'Entry' 
 
C:\Users\Timothy\Desktop> 

我尝试将 int() 添加到条目中,但它不起作用

请您参考如下方法:

您需要调用 radius.get() 来获取 Entry 小部件的当前值。 这是一些 documentation在上面。

您的代码中还有一些其他错误和拼写错误,所以我修复了它们并使它更多 PEP 8 - Style Guide for Python Code合规。

结果如下:

from math import pi 
from tkinter import * 
 
 
screen = Tk() 
screen.title("Area of Circle Calculator") 
screen.geometry("500x500") 
 
def submit(): 
    r = float(radius.get()) 
    an = pi * r**2 
    load = Label(screen, text="Hello %f" % (an)) 
    load.pack() 
 
ask = Label(screen, text="What is the radius of the circle?") 
ask.pack() 
 
radius = Entry(screen) 
radius.pack() 
 
done = Button(screen, text="submit", command=submit) 
done.pack() 
 
screen.mainloop()