【问题标题】:How to get the value of an Entry created in a def?如何获取在 def 中创建的条目的值?
【发布时间】:2021-03-27 12:03:44
【问题描述】:

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

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

这里是代码,顺便说一句,Entry 必须由定义创建...

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()

感谢每一个反馈:)

【问题讨论】:

  • t2=Button(test,text="Validate",command=calcul) -> t2=Button(test,text="Validate",command=lambda :calcul(value))

标签: python tkinter tkinter-entry


【解决方案1】:

您可以像这样使变量成为全局变量:

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))

【讨论】:

    【解决方案2】:

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

    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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-04
      • 2014-02-17
      • 2016-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多