如何获取在def中创建的条目的值?

2024-10-16 17:23:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理一个项目,我想获取在def中创建的条目的值(通过Tkinter上的按钮打开)

因此,我有我的tkinter主菜单,带有一个按钮,该按钮将调用def“panier”。 def“panier”正在创建条目“value”和另一个按钮以调用第二个def“calcul”。 第二个定义“calcul”将处理条目的值。。。 但是,在def“calcul”中,当我尝试执行value.get()时,它会告诉“NameError:name'value'未定义”

这是代码,顺便说一句,条目必须由定义创建

from tkinter import *

def panier():
    value=Entry(test)
    value.pack()
    t2=Button(test,text="Validate",command=calcul)
    t2.pack()

def calcul(value):
    a=value.get()
    #here will be the different calculations I'll do

test=Tk()

t1=Button(test,text="Button",command=panier)
t1.pack()

test.mainloop()

感谢所有反馈:)


Tags: texttest目的get定义valuetkinterdef
2条回答

可以将变量设置为全局变量,如下所示:

from tkinter import *

def panier():
    global value
    value = Entry(test)
    value.pack()
    t2 = Button(test, text="Validate", command=calcul)
    t2.pack()

def calcul():
    a = value.get()
    print(a)
    #here will be the different calculations I'll do

test = Tk()

t1 = Button(test, text="Button", command=panier)
t1.pack()

test.mainloop()

global value行使变量成为全局变量,因此您可以在程序中的任何位置使用它

您还可以像@JacksonPro建议的那样将变量作为参数传入 t2 = Button(test, text="Validate", command=lambda: calcul(value))

这是一种方法。全局创建集合(列表或字典)以保存对条目的引用。创建条目时,将其添加到集合中。我用一个列表或字典来保存引用,所以在所有三个地方切换注释的变体,尝试两种方法

import tkinter as tk

def panier():
    for item in ('value', ):
        ent = tk.Entry(test)

        collection.append(ent)
        # collection[item] = ent

        ent.pack()
    
    t2 = tk.Button(test,text="Validate",command=calcul)
    t2.pack()


def calcul():

    a = collection[0].get()
    # a = collection['value'].get()

    print(a)

collection = []
# collection = {}

test = tk.Tk()

t1 = tk.Button(test, text="Button", command=panier)
t1.pack()

test.mainloop()

相关问题 更多 >