Python 如何在Tkinter中刷新我的程序?
顺便说一句,我还是个初学者。。。所以基本上我要做的是用Tkinter编写一个简单的GUI来计算一个二次方程的解,用户只需给出方程的a,b和c,程序在点击“计算”按钮后在文本小部件中显示结果,我已经做得很好了,但是它仍然不想用结果来刷新文本小部件,而不是“现在没什么可看的”~!我该怎么办?返回Python 如何在Tkinter中刷新我的程序?,python,user-interface,tkinter,Python,User Interface,Tkinter,顺便说一句,我还是个初学者。。。所以基本上我要做的是用Tkinter编写一个简单的GUI来计算一个二次方程的解,用户只需给出方程的a,b和c,程序在点击“计算”按钮后在文本小部件中显示结果,我已经做得很好了,但是它仍然不想用结果来刷新文本小部件,而不是“现在没什么可看的”~!我该怎么办?返回解决方案没有任何作用,因为Tkinter只会丢弃函数的结果。您需要从calculate中更新结果文本 from Tkinter import * from cmath import sqrt window
解决方案
没有任何作用,因为Tkinter只会丢弃函数的结果。您需要从calculate
中更新结果文本
from Tkinter import *
from cmath import sqrt
window = Tk()
solution = "Nothing to see for now ~"
a = Entry(window)
a.pack()
b = Entry(window)
b.pack()
c = Entry(window)
c.pack()
result_text = Text(window)
result_text.pack()
def calculate():
na = int(a.get())
nb = int(b.get())
nc = int(c.get())
delta = (nb **2) - (4 * na * nc )
if delta > 0:
x1 = ((- nb) + sqrt(delta)) / (2 * na)
x2 = ((- nb) - sqrt(delta)) / (2 * na)
solution = "x1 = " + str(x1) + "\n x2 = " + str(x2)
return solution
elif delta==0:
x = (-nb) / (2 * na)
solution = "x1 = " + str(x)
return solution
else:
solution = "There isn't any solution for this equation."
return solution
button = Button(window , text = "Calculate" , command = calculate)
button.pack()
result_text.insert(END,solution)
mainloop()
calculate
中的返回值从未在任何地方使用过-您需要更新该函数中的文本
。“0.0”不是正确的文本索引。行从一开始计数,因此文本小部件的第一个索引是“1.0”
。
def calculate():
na = int(a.get())
nb = int(b.get())
nc = int(c.get())
delta = (nb **2) - (4 * na * nc )
if delta > 0:
x1 = ((- nb) + sqrt(delta)) / (2 * na)
x2 = ((- nb) - sqrt(delta)) / (2 * na)
solution = "x1 = " + str(x1) + "\n x2 = " + str(x2)
elif delta==0:
x = (-nb) / (2 * na)
solution = "x1 = " + str(x1) + "\n x2 = " + str(x2)
else:
solution = "There isn't any solution for this equation."
result_text.delete("1.0", END)
result_text.insert(END, solution)