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

如何通过Tkinter按钮创建并修改全局变量?

Tkinter Button Not Modifying Global Variable As Expected

Hey there, let's break down what's going on with your code and fix it step by step.

First, let's clear up the immediate issue you might be hitting (even if you mentioned seeing .txt output): your print(filename) runs before the Tkinter main loop starts, and at that point, the filename variable hasn't been defined at all—since createFile() only runs when you click the button. That should throw a NameError unless you accidentally had a leftover filename variable from a prior test run.

Next, the core confusion: when you click the button, filename does get updated, but you're not checking it at the right time. The initial print(filename) only runs once at startup, not after the button is clicked.

Fixed Code Example

Let's adjust your code to make the variable behavior clear and functional:

import tkinter as tk

# Initialize the global variable first to avoid startup errors
filename = ""

def createFile():
    global filename
    entry1_value = entry1.get()
    filename = entry1_value + ".txt"
    # Add this to confirm the variable updates when the button is clicked
    print(f"After button click: filename is now → {filename}")

root = tk.Tk()
root.title("File name selection")
root.geometry("300x200")

label1 = tk.Label(root, text="Enter file name:", font="Helvetica 12")
label1.place(x=100, y=60)

entry1 = tk.Entry(root, font="Helvetica 12")
entry1.place(x=70, y=85)

button1 = tk.Button(root, text="Create file", font="Helvetica 12", command=createFile)
button1.place(x=110, y=110)

# This runs once at startup, shows the initial empty value
print(f"At program start: filename is → {filename}")

root.mainloop()

# This runs after you close the window, shows the final value of filename
print(f"After window closes: final filename is → {filename}")

Key Changes Explained

  • Pre-initialize the global filename: This eliminates the NameError that would pop up when the initial print runs before any button clicks.
  • Add a print inside createFile(): This lets you immediately confirm that the global variable is being updated the moment you click the button.
  • Print after mainloop(): Since root.mainloop() runs until you close the window, this line will show you the final state of filename after all your button interactions.

Why Your Original Code Seemed Broken

Your original print(filename) only executed once at launch—before you ever clicked the button. If you saw .txt output, that was likely from a leftover filename variable from a previous test where you had an empty entry. But once you click the button, filename does get updated—you just had no code checking that update after the click.

Give this adjusted code a test: type something into the entry, click the button, and you'll see the updated filename in the console right away. Close the window, and you'll see the final value printed one last time.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:34:53