You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python新手求助:基于Tkinter实现按计数显示圆周率小数位功能

Fixing Your Pi Decimal Tkinter App

Hey there! Let's get your Tkinter app working properly so it shows the next decimal digit of π every time you click the "下一位" button. First, let's go over the issues in your current code, then jump to the corrected version.

Issues in Your Original Code

  • The pi_decimal() function has a syntax error (missing colon after while counter > 0) and isn't even used anywhere.
  • Your Decimals() function only increments the counter but doesn't actually fetch the corresponding decimal digit from your pi string to display.
  • You reference display_decimal but never create this label widget, and there's no button added to trigger the function.
  • The pi string you have starts with the first decimal digit of π, but we need to make sure we index it correctly as the counter increases.

Corrected Full Code

# Import tkinter with a namespace (best practice to avoid naming conflicts)
import tkinter as tk

# Backend setup
counter = 0
# This is the decimal part of π after 3. (3.15926...)
pi_decimals = '159265358979323846'

def show_next_decimal():
    global counter
    # Make sure we don't go beyond the length of our stored decimals
    if counter < len(pi_decimals):
        counter += 1
        # Get the current decimal digit (index is counter-1 since we start counting from 1)
        current_digit = pi_decimals[counter-1]
        # Update the label to show both the position and the digit
        display_label['text'] = f"第 {counter} 位小数:{current_digit}"
    else:
        # If we've shown all digits, let the user know
        display_label['text'] = "没有更多小数位啦!"

# Create the main window
app_window = tk.Tk()
app_window.title("π小数查看器")

# Create the label to display the decimal digit
display_label = tk.Label(app_window, text="点击按钮查看π的第1位小数", font=('Arial', 14))
display_label.pack(pady=20)

# Create the "下一位" button
next_button = tk.Button(app_window, text="下一位", command=show_next_decimal, font=('Arial', 12))
next_button.pack(pady=10)

# Start the main event loop
app_window.mainloop()

Key Improvements Explained

  • Better Import Practice: Using import tkinter as tk instead of from tkinter import * prevents accidental naming conflicts with your own variables/functions.
  • Boundary Check: We added a check to make sure we don't try to access an index beyond our stored pi_decimals string—this avoids crashes and tells the user when there are no more digits left.
  • Useful Display: The label now shows both the position of the decimal digit and the digit itself, making the app more intuitive.
  • Proper Widget Setup: We actually create the display label and button, then use pack() to add them to the window so they're visible.

内容的提问来源于stack exchange,提问作者IceD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:18:11