首页 > 解决方案 > 如何在 tkinter 中创建一个条目 int

问题描述

我想创建一个圆形计算器区域,因为我有一些空闲时间所以我尝试先在终端中运行它并且它可以工作但是当我决定添加一个小 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() 添加到条目中,但它不起作用

标签: pythontkinter

解决方案


您需要调用radius.get()以获取Entry小部件的当前值。这是有关它的一些文档

您的代码中还有一些其他错误和拼写错误,因此我修复了它们并使其更符合PEP 8 - Python 代码样式指南

结果如下:

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()

推荐阅读