我是python的新手。我的問題是:我可以使用一個按鈕「估計」多少次來計算我的答案?更具體地說,該項目是將牛頓公式應用到tkinter中。如果輸入爲0,那麼估計變量文本框的計算結果爲0.如果輸入是正數,我應該能夠使用估計按鈕作爲循環多次處理該數字。我很容易使用嵌套while循環獲得最終結果。但是,試圖重複使用估計按鈕逐步進入算法似乎是不可能的。我已經嘗試了一切。最接近的我是設置我的inputVar複製我的estimateVar,但這顯然會導致邏輯錯誤,因爲輸入需要保持不變。此外,我已經嘗試設置一個全局變量的估計,但python不會允許我操縱估計,我的inputVar返回全局值。估計的初始值必須是1.如果有人有任何意見,我們將不勝感激。這裏是我的代碼使用tkinter /使用按鈕進行多次計算的牛頓方程式
'''
Created on Nov 11, 2015
@author: lz206729
'''
from tkinter import *
class newtonGUI(Frame):
def __init__(self):
#Sets up window
Frame.__init__(self)
self.master.title("Newton's Square")
self.grid(column = 0, row = 0)
#Label and field for number input
self._inputLabel = Label(self, text = "Input a positive number to square: ")
self._inputLabel.grid(row = 0, column = 0)
self._inputVar = DoubleVar()
self._inputEntry = Entry(self, textvariable = self._inputVar)
self._inputEntry.grid(row = 0, column = 1)
#Displays the common square root
self._estimateLabel = Label(self, text = "The estimate is : ")
self._estimateLabel.grid(row = 1, column = 0)
self._estimateVar = DoubleVar()
self._estimateEntry = Entry(self, textvariable = self._estimateVar)
self._estimateEntry.grid(row = 1, column = 1)
#Button that computes the input
self._estimateButton = Button(self, text = "Estimate", command = self._newtonSquare)
self._estimateButton.grid(row = 4, column = 0)
#Button that resets text boxes
self._resetButton = Button(self, text = "Reset", command = self._reset)
self._resetButton.grid(row = 4, column = 1)
def _newtonSquare(self):
tolerance = 0.000001
estimate = 1
x = self._inputVar.get()
if x == 0:
self._estimateVar.set(x/2)
else:
while True:
estimate = (estimate + x/estimate)/2
difference = abs(x - estimate **2)
if difference <= tolerance:
break
self._estimateVar.set(estimate)
def _reset(self):
self._inputVar.set(0)
self._estimateVar.set(0)
self._estimateButton.config(state='normal')
def main():
newtonGUI().mainloop()
main()
牛頓廣場?!你是什麼天才? –