当前是Python的初学者。
我正在尝试基于PI创建一个简单的TKINTER应用程序(3.14( 每当他们按"下一个数字"时,都会增加计数器 1并显示 下一个小数。
# Import the Tkinter functions
from tkinter import *
#####backend function
global counter
counter = 0
pi = '159265358979323846'
def pi_decimal():
while counter > 0
pass
def Decimals():
global counter
counter +=1
display_decimal['text'] = counter
# Create a window
application_window = Tk()
# Give the window a title
application_window.title('PI')
# create a button for application window
my_button = Button(application_window,
text = 'Next Digit', command = Decimals)
#create a row that shows the number
number_pi = Label(application_window, text = pi)
display_decimal = Label(application_window, text = counter)
#put button into the window
display_decimal.pack()
number_pi.pack()
my_button.pack()
例如,我试图弄清楚如何浏览最多18的小数列表,例如,添加到3.14中。计数器0 = 3.14,计数器1 = 3.141,计数器2 = 3.1415等。
您可以做这样的事情:
您的应用程序主要缺少对Mainloop的电话。
# Import the Tkinter functions
import tkinter as tk
def decimals():
global counter
counter += 1
try:
text = pi[counter]
except IndexError:
counter = 0
text = ''
display_decimal['text'] = f"PI decimal value: {text}"
display_decimal_ndx['text'] = f"PI decimal index: {counter}"
if __name__ == '__main__':
# backend function
counter = 0
pi = '159265358979323846'
# Create a window
application_window = tk.Tk()
# Give the window a title
application_window.title('PI')
# create a button for application window
my_button = tk.Button(application_window,
text='Next Digit', command=decimals)
# create a row that shows the number
number_pi = tk.Label(application_window, text = pi)
display_decimal = tk.Label(application_window, text='')
display_decimal_ndx = tk.Label(application_window, text=counter)
# put button into the window
display_decimal.pack()
display_decimal_ndx.pack()
number_pi.pack()
my_button.pack()
application_window.mainloop()
注意:
您可能需要考虑使用import tkinter as tk
而不是混乱的全局名称空间。
枚举完成后,功能decimals()
中的try/except
块避免了讨厌的索引错误。
标签显示显示哪个小数,另一个显示其值。
完成后,将枚举重置为第一个小数。
编辑:
您可以执行类似的操作,以添加数字pi的显示,该数字pi更新在按下按钮时显示的小数数:
import tkinter as tk
def decimals():
global counter
counter += 1
try:
text = pi[counter]
except IndexError:
counter = 4
text = ''
display_decimal['text'] = f"PI decimal value: {text}"
display_decimal_ndx['text'] = f"PI decimal index: {counter}"
number_pi['text'] = pi[:counter+1]
if __name__ == '__main__':
# backend function
counter = 4
pi = '3.14159265358979323846'
# Create a window
application_window = tk.Tk()
# Give the window a title
application_window.title('PI')
# create a button for application window
my_button = tk.Button(application_window,
text='Next Digit', command=decimals)
# create a row that shows the number
number_pi = tk.Label(application_window, text = pi[:counter+1])
display_decimal = tk.Label(application_window, text='')
display_decimal_ndx = tk.Label(application_window, text=counter)
# put button into the window
display_decimal.pack()
display_decimal_ndx.pack()
number_pi.pack()
my_button.pack()
application_window.mainloop()