我正在制作一个简单的Python Tk计算器,但是有一个错误:计算器将无法工作,除非我按下其中一个按钮然后在我执行此操作时放入数字它会显示“输入数字”的错误值!”在它之后,它将计算输入数字,但如果我只是打开它并输入数字它将无法正常工作
这是我的代码:
from Tkinter import *
import math
def calculate():
try:
num1 = float(enter1.get())
num2 = float(enter2.get())
result = num1 * num2
label3.config(text=str(result))
except ValueError:
label3.config(text='Enter numeric values!', fg="white")
def calculate2():
try:
num1 = float(enter1.get())
num2 = float(enter2.get())
result = num1 / num2
label3.config(text=str(result))
except ValueError:
label3.config(text='Enter numeric values!', fg="white")
def calculate3():
try:
num1 = float(enter1.get())
num2 = float(enter2.get())
result = num1 + num2
label3.config(text=str(result))
except ValueError:
label3.config(text='Enter numeric values!',fg="white")
def calculate4():
try:
num1 = float(enter1.get())
num2 = float(enter2.get())
result = num1 - num2
label3.config(text=str(result))
except ValueError:
label3.config(text='Enter numeric values!',fg="white")
def calculate5():
try:
num1 = float(enter1.get())
result = num1**2
label3.config(text=str(result))
except ValueError:
label3.config(text='Enter numeric values!',fg="white")
def calculate6():
try:
num1 = float(enter1.get())
result = math.sqrt(num1)
label3.config(text=str(result))
except ValueError:
label3.config(text='Enter numeric values!',fg="white")
root = Tk()
root.configure(background='black')
root.wm_title("Calc")
label1 = Label(root, text='First Number:',bg="black", fg="white")
label1.grid(row=0, column=0,columnspan=2)
enter1 = Entry(root, bg='white')
enter1.grid(row=1, column=0,columnspan=2)
label2 = Label(root, text='Second Number:',bg="black", fg="white")
label2.grid(row=2, column=0,columnspan=2)
enter2 = Entry(root, bg='white')
enter2.grid(row=3, column=0, columnspan=2)
btn1 = Button(root, text='-Multiply-', command=calculate, bg=" black",activebackground="green", fg="white")
btn1.grid(row=4, column=0)
btn2 = Button(root, text='-Divide-', command=calculate2, bg="black",activebackground="orange", fg="white")
btn2.grid(row=5, column=0)
btn3 = Button(root, text='-Add-', command=calculate3, bg="black",activebackground="purple", fg="white")
btn3.grid(row=5, column=1)
btn4 = Button(root, text='-Subtract-', command=calculate4, bg="black",activebackground="red", fg="white")
btn4.grid(row=4, column=1)
btn5 = Button(root, text='Square (Only First #)', command=calculate5, bg="black",activebackground="cyan", fg="white")
btn5.grid(row=6, column=0, columnspan=2)
btn6 = Button(root, text='Square Root (only First #)', command=calculate6, bg="black",activebackground="yellow", fg="white")
btn6.grid(row=7, column=0, columnspan=2,)
label3 = Label(root, bg="black")
label3.grid(row=8, column=0, columnspan=2)
enter1.focus()
enter1.bind('<Return>', func=lambda e:enter2.focus_set())
root.mainloop()
答案 0 :(得分:4)
您的代码没有任何问题,唯一的问题是文本颜色最初是黑色的。这就是为什么它在显示错误之前“有效”,因为该选项将fg
选项设置为白色,并且在下一次更改中它保持已配置的相同文本颜色。
要解决此问题,请在创建Label小部件时将fg
选项设置为"white"
:
label3 = Label(root, bg="black", fg="white")