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

如何用Python Tkinter实现按钮触发输入子窗口及a+b求和功能

How to Create a Tkinter Popup Window for Inputting and Calculating a+b

No worries, this is a straightforward task once you break down the components. Let's build this step by step with a complete, working example that handles edge cases (like non-numeric input) too.

Step 1: Basic Setup & Main Window

First, we'll create the main application window with a button that triggers the popup. We'll use Tk() for the main window and Button to call our popup function.

Step 2: Popup Window Logic

The popup will be a Toplevel() window (Tkinter's way of creating child windows). Inside it, we'll add:

  • Two input fields (Entry widgets) for a and b
  • A button to trigger the calculation
  • A label to display the result

Full Working Code

import tkinter as tk
from tkinter import messagebox

def open_calculator_popup():
    # Create the popup window
    popup = tk.Toplevel()
    popup.title("Calculate a + b")
    popup.geometry("300x200")
    popup.resizable(False, False)

    # Create labels and entry fields for a and b
    tk.Label(popup, text="Enter value for a:").pack(pady=5)
    entry_a = tk.Entry(popup, width=20)
    entry_a.pack(pady=5)

    tk.Label(popup, text="Enter value for b:").pack(pady=5)
    entry_b = tk.Entry(popup, width=20)
    entry_b.pack(pady=5)

    # Label to display result
    result_label = tk.Label(popup, text="Result: ", font=("Arial", 10, "bold"))
    result_label.pack(pady=10)

    def calculate_sum():
        try:
            # Get values from entries and convert to float
            a = float(entry_a.get())
            b = float(entry_b.get())
            total = a + b
            # Update result label
            result_label.config(text=f"Result: {total:.2f}")
        except ValueError:
            # Show error if input isn't a number
            messagebox.showerror("Invalid Input", "Please enter valid numbers for a and b!")

    # Add calculate button
    tk.Button(popup, text="Calculate", command=calculate_sum).pack(pady=5)

# Main application setup
root = tk.Tk()
root.title("Main Window")
root.geometry("200x100")

# Button to open popup
tk.Button(root, text="Open Sum Calculator", command=open_calculator_popup).pack(pady=30)

root.mainloop()

Key Explanations

  • Toplevel(): This creates a separate child window tied to the main root window. It inherits Tkinter's window management (like closing behavior).
  • Input Handling: We use float() to convert input values, and wrap it in a try-except block to catch cases where the user enters non-numeric text—this prevents the app from crashing.
  • Result Display: The result_label is updated dynamically using config() once the calculation is done.
  • Error Feedback: messagebox.showerror() gives the user clear feedback if they enter invalid input.

Optional: Pass Result Back to Main Window

If you want to display the result in the main window instead of just the popup, you can modify the code to update a label in the root window:

  1. Add a result label in the main window:
    main_result_label = tk.Label(root, text="Last Result: ", font=("Arial", 10))
    main_result_label.pack(pady=10)
    
  2. Modify the calculate_sum function to update this label via a closure:
    def open_calculator_popup(main_result_label):
        # ... existing popup code ...
        def calculate_sum():
            try:
                a = float(entry_a.get())
                b = float(entry_b.get())
                total = a + b
                result_label.config(text=f"Result: {total:.2f}")
                # Update main window label
                main_result_label.config(text=f"Last Result: {total:.2f}")
            except ValueError:
                messagebox.showerror("Invalid Input", "Please enter valid numbers for a and b!")
    
  3. Update the button command to pass the label:
    tk.Button(root, text="Open Sum Calculator", command=lambda: open_calculator_popup(main_result_label)).pack(pady=10)
    

This way, the result is visible in both the popup and the main window.

内容的提问来源于stack exchange,提问作者Rob-In

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:40:51