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

如何将Tkinter中Entry组件e1的值传入fahrradfuerhrdoku函数?

解决Tkinter中Entry组件访问报错的问题

问题原因

e1是button_searchdata函数内部定义的局部变量,fahrradfuerhrdoku函数的作用域里找不到这个变量,所以执行e1.get()时会报“e1未定义”的错误。下面是几种可行的解决方法:


方法一:使用全局变量

在两个函数中都用global关键字声明e1,让函数访问全局作用域的变量:

def fahrradfuerhrdoku():
    global e1
    print(e1.get())

def button_searchdata():
    global e1
    root = Tk()
    root.eval('tk::PlaceWindow . center')
    root.geometry('400x200')
    root.title("Fahrradsuche für HR Doku")
    Label(root, text="R-Nummer ohne R").place(x = 30, y = 72, width=100, height=50)
    e1 = Entry(root)
    e1.place(x = 150, y = 80, width=200, height=30)
    Button(root, text='suchen', command=fahrradfuerhrdoku).grid(row=3, column=1, sticky=W, pady=4)
    root.mainloop()

方法二:用Lambda传递参数

通过Lambda表达式把e1作为参数传给回调函数,不需要全局变量:

def fahrradfuerhrdoku(entry_widget):
    print(entry_widget.get())

def button_searchdata():
    root = Tk()
    root.eval('tk::PlaceWindow . center')
    root.geometry('400x200')
    root.title("Fahrradsuche für HR Doku")
    Label(root, text="R-Nummer ohne R").place(x = 30, y = 72, width=100, height=50)
    e1 = Entry(root)
    e1.place(x = 150, y = 80, width=200, height=30)
    # 用Lambda捕获e1并传给回调函数
    Button(root, text='suchen', command=lambda: fahrradfuerhrdoku(e1)).grid(row=3, column=1, sticky=W, pady=4)
    root.mainloop()

方法三:用类封装(推荐)

对于GUI程序,用类管理组件和逻辑更规范,也方便后续扩展:

import tkinter as tk
from tkinter import Tk, Label, Entry, Button

class FahrradSucheApp:
    def __init__(self, root):
        self.root = root
        self.root.eval('tk::PlaceWindow . center')
        self.root.geometry('400x200')
        self.root.title("Fahrradsuche für HR Doku")
        
        Label(root, text="R-Nummer ohne R").place(x = 30, y = 72, width=100, height=50)
        self.e1 = Entry(root)
        self.e1.place(x = 150, y = 80, width=200, height=30)
        Button(root, text='suchen', command=self.fahrradfuerhrdoku).grid(row=3, column=1, sticky=W, pady=4)
    
    def fahrradfuerhrdoku(self):
        print(self.e1.get())

def button_searchdata():
    root = Tk()
    app = FahrradSucheApp(root)
    root.mainloop()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 22:33:25