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

Python tkinter如何获取Entry姓名输入供messagebox调用,onClick找不到myInput变量

问题原因

你遇到的是Python变量作用域问题:myInput是在show1()函数内部定义的局部变量,仅能在show1函数内部访问,onClick函数不在它的作用域范围内,自然无法识别这个变量。
此外要获取Entry控件的输入内容,不能直接将控件对象拼接到字符串中,需要调用控件的get()方法,或者用你已经绑定的StringVar对象的get()方法取值。

解决方案

你已经提前给Entry控件绑定了全局的Input1变量,直接用这个变量取值是最简单的方案,不需要额外调整变量作用域:
把onClick函数修改为如下内容即可正常运行:

def onClick():
    # 用绑定的StringVar的get方法获取输入内容
    name = Input1.get()
    tk.messagebox.showinfo("Your name", f"Your name - {name}")

如果后续需要对Entry控件做更多操作,也可以将myInput声明为全局变量:

  1. 在show1函数内部开头添加global myInput声明,将局部变量升级为全局变量
  2. onClick函数中调用myInput.get()获取输入值即可

修正后完整可运行代码

import tkinter as tk
from tkinter import *
from tkinter import messagebox

# window settings
win = Tk()
win.geometry("250x350")
win.resizable(0,0)
win.title("Test app")

# def and other
Input1 = StringVar()
def show1():
    myLabel3 = Label(win, text="I love Python :)", font=("Montserrat", 18), highlightbackground='darkred', highlightthickness=3)
    myLabel3.place(x=30, y=130)
    myLabel4 = Label(win, text="Now, enter your name!", font=("Montserrat", 15))
    myLabel4.place(x=5, y=190)
    myInput = Entry(win, font=("Montserrat", 17), textvariable=Input1, width=100, justify=LEFT)
    myInput.place(x=0, y=240)
    Button2 = Button(win, text="Apply", font=("Montserrat"), command=onClick)
    Button2.place(x=90, y=290)
def onClick():
    name = Input1.get()
    tk.messagebox.showinfo("Your name", f"Your name - {name}")
# widgets
myLabel1 = Label(win, text="Hello World!", font=("Montserrat", 20))
myLabel2 = Label(win, text="Click this button!", font=("Montserrat", 16))
Button1 = Button(win, text="Click me pls!", font=("Montserrat"), command=show1)

# widgets settings
myLabel1.place(x=35)
myLabel2.place(x=26, y=40)
Button1.place(x=62, y=83)

win.mainloop()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 07:24:01