我试图使用Pycharm和tkinter制作一个简单的简单兴趣计算器。
有我的代码 显示x尚未定义
我已经尝试将变量设置为全局变量。
我也无法在我的finalProgram函数中调用该函数,因为它使它成为无穷循环
from tkinter import *
def mainWindow():
label = Label(frame, text = "What do you want to do")
label.pack()
but1 = Button(frame, text = "SI", command = SimpleInterest)
but1.pack()
def SimpleInterest():
global x
frame.destroy()
label5 = Label(frame2,text="Please enter principal amount" )
label5.pack()
p = Entry(frame2 )
p.pack()
label6 = Label(frame3,text="Please ROI")
label6.pack()
r = Entry(frame3, text="Please enter rate of interest")
r.pack()
label7 = Label(frame4, text="Please enter time")
label7.pack()
t = Entry(frame4, text="Please enter time")
t.pack()
buttonmain = Button(frame4, text = "Finlise", command = finalProgram)
buttonmain.pack()
global x
x =(p*r*t)/100
def finalProgram():
frame2.destroy()
frame3.destroy()
frame4.destroy()
global x
newlabel = Label(frame5, text = x)
root = Tk()
frame = Frame(root)
frame.grid(row=0,columnspan = 2)
mainWindow()
frame2 = Frame(root)
frame2.grid(row = 0, columnspan =2)
frame3 = Frame(root)
frame3.grid(row =1, columnspan =2)
frame4 = Frame(root)
frame4.grid(row=2, columnspan =2)
frame5 = Frame(root)
frame5.grid(row=0)
root.mainloop()
答案 0 :(得分:1)
您的代码只有一种修改。在下部添加了一行:
x = 0.0
这是为了确保您在全局范围内具有变量x
。有了全局范围内的变量,您就可以在函数中使用(读取和写入)它(在您用global x
声明为全局变量之后)
from tkinter import *
def mainWindow():
label = Label(frame, text = "What do you want to do")
label.pack()
but1 = Button(frame, text = "SI", command = SimpleInterest)
but1.pack()
def SimpleInterest():
global x
frame.destroy()
label5 = Label(frame2,text="Please enter principal amount" )
label5.pack()
p = Entry(frame2 )
p.pack()
label6 = Label(frame3,text="Please ROI")
label6.pack()
r = Entry(frame3, text="Please enter rate of interest")
r.pack()
label7 = Label(frame4, text="Please enter time")
label7.pack()
t = Entry(frame4, text="Please enter time")
t.pack()
buttonmain = Button(frame4, text = "Finlise", command = finalProgram)
buttonmain.pack()
global x
x =(p*r*t)/100
def finalProgram():
frame2.destroy()
frame3.destroy()
frame4.destroy()
global x
newlabel = Label(frame5, text = x)
x = 0.0
root = Tk()
frame = Frame(root)
frame.grid(row=0,columnspan = 2)
mainWindow()
frame2 = Frame(root)
frame2.grid(row = 0, columnspan =2)
frame3 = Frame(root)
frame3.grid(row =1, columnspan =2)
frame4 = Frame(root)
frame4.grid(row=2, columnspan =2)
frame5 = Frame(root)
frame5.grid(row=0)
root.mainloop()
请注意,这只是针对您所问问题的快速修复。代码的总体结构并不是很好,您应该考虑学习诸如类的概念和/或如何将参数传递给函数。