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

如何在Python Tkinter中实现点击按钮将no_scatter函数结果保存至本地纯文本文件

Fix: Save Tkinter Button's Generated Content to a Text File

Got it, let's get your button working to save the generated G-code to a local text file properly. Here's the fully updated code, followed by breakdowns of the key fixes:

import tkinter as tk
from tkinter import filedialog, messagebox
import os
os.system('clear')

root = tk.Tk()
root.title('Test File')
root.geometry("400x1000")
root.configure(bg='light grey')

def no_scatter():
    # First, validate the input is a number
    try:
        core_height = float(e1.get())
    except ValueError:
        messagebox.showerror("Oops!", "Please enter a valid number for Core Height.")
        return
    
    # Build blockone as a properly formatted string
    blockone_parts = [
        'G20', 'G90', 'M3S200',
        f'G1X{core_height * .125:.5f}F20',
        f'G1X{core_height * .25:.5f}F15',
        f'G1X{core_height * .375:.5f}F10',
        f'G1X{core_height * .5:.5f}F20S300',
        f'G1X{core_height * .625:.5f}F10',
        f'G1X{core_height * .75:.5f}F10',
        f'G1X{core_height * .875:.5f}F15',
        f'G1X{core_height:.5f}F20S600',
        f'G1X{core_height * .875:.5f}F20',
        f'G1X{core_height * .75:.5f}F15',
        f'G1X{core_height * .625:.5f}F10',
        f'G1X{core_height * .5:.5f}F10S1200',
        f'G1X{core_height * .375:.5f}F10',
        f'G1X{core_height * .25:.5f}F10',
        f'G1X{core_height * .125:.5f}F15',
        'G1X0.000F20'
    ]
    blockone = ' '.join(blockone_parts)
    
    # Build blocktwo as a properly formatted string
    blocktwo_parts = [
        f'G1X{core_height * .125:.5f}F20',
        f'G1X{core_height * .25:.5f}F15',
        f'G1X{core_height * .375:.5f}F10',
        f'G1X{core_height * .5:.5f}F20',
        f'G1X{core_height * .625:.5f}F10',
        f'G1X{core_height * .75:.5f}F10',
        f'G1X{core_height * .875:.5f}F15',
        f'G1X{core_height:.5f}F20',
        f'G1X{core_height * .875:.5f}F20',
        f'G1X{core_height * .75:.5f}F15',
        f'G1X{core_height * .625:.5f}F10',
        f'G1X{core_height * .5:.5f}F10',
        f'G1X{core_height * .375:.5f}F10',
        f'G1X{core_height * .25:.5f}F10',
        f'G1X{core_height * .125:.5f}F15',
        'G1X0.000F20'
    ]
    blocktwo = ' '.join(blocktwo_parts)
    
    # Combine all content into one string matching your desired format
    final_content = blockone + ' ' + (' ' + blocktwo) * 100
    
    # Let user choose where to save the file
    save_path = filedialog.asksaveasfilename(
        defaultextension=".txt",
        filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")]
    )
    
    if save_path:
        # Write the content to the selected file
        with open(save_path, 'w') as output_file:
            output_file.write(final_content)
        messagebox.showinfo("Success!", "Your G-code file has been saved.")

# Create UI elements
myLabel = tk.Label(root, text='Enter Core Height', bg='light grey')
myLabel.pack(pady=10)

e1 = tk.Entry(root, width=10, justify='center', border=0)
e1.pack()

tk.Button(root, text='No Scatter', command=no_scatter).pack(pady=10)

root.mainloop()

Key Fixes & Improvements:

  • Fixed String Construction: Your original code was creating tuples (not strings) for blockone and blocktwo because of commas between elements. We now use lists of formatted strings (via f-strings for clean decimal values) and join them with spaces to match your sample output.
  • Added File Saving Logic: We use filedialog.asksaveasfilename() to let you pick a save location (no more random blank windows!). Once you select a path, we write the combined G-code directly to the file.
  • Input Validation: Added a try-except block to catch non-numeric inputs and show a friendly error message, preventing crashes.
  • Cleaned Up Syntax: Removed redundant from tkinter import * (using tk. prefixes avoids namespace conflicts) and organized code for readability.
  • Proper Content Combination: Instead of creating a tuple with blockone, blocktwo * 100, we concatenate the strings correctly to produce a single continuous line of G-code like your sample.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 11:08:12