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

为何向函数传递StringVar作为参数无法正常工作?

问题分析与解决

你的代码存在两个核心问题,导致无法正常获取输入框内容并写入文件:

  1. 按钮command参数的错误赋值
    你写的command = ecrire()会在程序启动时立即执行ecrire函数,而不是等待按钮点击时触发。而且这里没有传入ligne参数,不仅会引发参数缺失的报错,还会因为启动时输入框还未被输入内容,即使强行执行也只能拿到空值。

  2. 缺少带参数函数的调用方式
    Tkinter按钮的command默认仅支持无参函数,要传递参数需要用lambda来包装函数调用。

修正后的代码

# coding: utf-8

from tkinter import *

fenetre = Tk()
labl = Label(fenetre, text = "Bonjour, monde !")
bouton=Button(fenetre, text="Fermer", command=fenetre.quit)

def ecrire(ligne):
    # 用with语句自动管理文件生命周期,避免遗漏关闭操作
    with open("save.txt", "a", encoding="utf-8") as file:
        message = ligne.get()
        file.write(message + "\n")

string = StringVar()
entree = Entry(fenetre, textvariable=string, width=10)
# 用lambda包装函数,确保点击按钮时才调用ecrire并传入string参数
btnEcrire = Button(fenetre, text="ecrire", command=lambda: ecrire(string))

labl.pack()
entree.pack()
btnEcrire.pack()
bouton.pack()

fenetre.mainloop()

关键说明

  • lambda: ecrire(string)会创建一个无参的匿名函数,点击按钮时才会执行ecrire(string),完美适配Tkinter按钮的command要求。
  • 使用with open(...)语法可以自动关闭文件,同时指定encoding="utf-8"能避免写入中文等非ASCII字符时出现乱码问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 20:47:16