首页 > 解决方案 > 我想从条目中获取一个值,但这没有用

问题描述

问题是:

return self.func(*args)
TypeError: b1_pg() missing 1 required positional argument: 'e1'

我搜索了整个谷歌,但我没有找到任何东西

from tkinter import *
from tkinter import ttk
from functools import partial

root = Tk()
root.geometry('400x200+100+200')
def b1_pg(e1):
    search = str(e1.get())
    print(search)
    return search

what = ttk.Label(root, text="who do you want to search about???").grid(row=1, column=0)

e1 = ttk.Entry(root, width=40).grid(row=1, column=1)

b1 = ttk.Button(root, text="if you are ready prees here", command=b1_pg).grid(row=2, column=0)

#information=ttk.Label(root,text=family{search})

root.title('family')
root.mainloop()

当我按下按钮时,我希望代码从 e1(entry) 中获取值,但它给了我一个错误

return self.func(*args)
TypeError: b1_pg() missing 1 required positional argument: 'e1'

我的代码有什么问题?

标签: python-3.xtkinterfunctools

解决方案


你有几件事我们需要在这里更正。

grid()您在定义条目字段的同一行上使用的一个问题。因此,由于以这种方式分配,e1实际上总是会返回。Nonegrid()

要解决此问题,您可以e1.grid()在新行上执行此操作,这将使您可以e1.get()毫无问题地使用。

也就是说,让您更正您的导入,因为*您最终会覆盖方法。

所以不要这样做:

从 tkinter 导入 *

做这个:

import tkinter as tk

我们还应该更改您的函数中的一些内容。

return部分不会在这里做任何有用的事情。您不能将值返回给调用该函数的按钮。它不能以任何方式使用,因此您可以删除该行。如果您需要在某处使用该值,则可以将其从函数发送到您需要的任何地方。

与您在问题中的错误有关。您的函数中不需要参数e1。您首先没有将参数传递给函数,因此这将导致错误。其次,您已经从全局命名空间调用 e1.get(),因此不需要参数。

最后你不需要这样做str(e1.get())。该get()方法已经返回一个字符串。它总是会返回一个字符串。

请参阅下面的代码,如果您有任何问题,请告诉我:

import tkinter as tk
import tkinter.ttk as ttk

root = tk.Tk()
root.title('family')
root.geometry('400x200+100+200')


def b1_pg():
    search = e1.get()
    print(search)


ttk.Label(root, text="who do you want to search about???").grid(row=1, column=0)
e1 = ttk.Entry(root, width=40)
e1.grid(row=1, column=1)
ttk.Button(root, text="if you are ready press here", command=b1_pg).grid(row=2, column=0)

root.mainloop()

推荐阅读