所以我正在尝试构建一个简单的计算器,它显示数字pi,即3.14中的标签,每次单击“点击我”按钮它会添加另一个十进制值3.14。例如,一旦点击,标签将显示3.141,第二次显示:3.1415等。
以下是代码:
# Import the Tkinter functions
from Tkinter import *
# Create a window
loan_window = Tk()
loan_window.geometry('{}x{}'.format(500, 100))
# Give the window a title
loan_window.title('Screeen!')
## create the counter
pi_num = 3.14
# NUMBER frame
frame = Frame(loan_window, width=100, height=50)
frame.pack()
def addPlaceValue():
pi_num= 3.14
return pi_num
## create a label and add it onto the frame
display_nums = Label(frame, text = 'pi_num')
display_nums.pack()
#### create a label and add it onto the frame
##display_nums = Label(frame, text = pi_num)
##display_nums.pack()
##
# Create a button which starts the calculation when pressed
b1 = Button(loan_window, text = 'Click me', command= addPlaceValue, takefocus = False)
b1.pack()
# Bind it
loan_window.bind('<Return>', addPlaceValue())
# event loop
loan_window.mainloop()
我已多次尝试跟踪按钮点击次数,但未能这样做。我看到一个问题;代码不知道点击按钮的第n次。有什么想法吗?
答案 0 :(得分:0)
我不知道你如何pi
存储数字位数....但是,这是一种非常容易指定精度的方法(让我们说精度为100):
from sympy import mpmath
mpmath.dps = 100 #number of digits
PI = str(mpmath.pi)
PI是一个常量实例,并且不是自然可订阅的,因此我们将其转换为str
以便以后编制索引。
现在,至于更新文本,我们可以在每次放置按钮时跟踪计数器。
我们可以将此计数器设置为loan_window
的属性,默认值为4
,以显示pi 3.14
的最常见表示形式,然后递增并更改标签文字:
编辑:绑定时你也想传递函数名而不是function_name()
这实际上是调用函数
import sympy, Tkinter as tk
sympy.mpmath.dps = 100
PI = str(sympy.mpmath.pi)
loan_window = tk.Tk()
loan_window.counter = 4
frame = tk.Frame(loan_window, width=100, height=50)
frame.pack()
def addPlaceValue():
loan_window.counter += 1
display_nums['text'] = PI[:loan_window.counter]
display_nums = tk.Label(frame, text = PI[:loan_window.counter])
display_nums.pack()
b1 = tk.Button(loan_window, text = 'Click me', command= addPlaceValue, takefocus = False)
b1.pack()
loan_window.bind('<Return>', addPlaceValue)
loan_window.mainloop()