【问题标题】:Calling back the function in button回调按钮中的函数
【发布时间】:2017-11-15 00:47:51
【问题描述】:

我收到了关于这个主题的帮助:comparing values from different dataframes line by line, python

我有一个代码,在我的 tk inter 程序中:

DF1 = pd.DataFrame({"X":[1,2,3,4,5,6],"Y":[1,2,3,4,5,6],"C":[12,22,33,45,13,56]})

DF2 = pd.DataFrame({"X":[1,5],"Y":[1,1],"X1":[5,1],"Y1":[5,5]})

def isInSquare(row, df2):
    c1 =  (row.X > df2.iloc[0].X) and (row.Y > df2.iloc[0].Y)
    c1 = c1 and  (row.X < df2.iloc[0].X1) and (row.Y < df2.iloc[0].Y1)
    c1 = c1 and (row.X < df2.iloc[1].X) and (row.Y > df2.iloc[1].Y)
    c1 = c1 and (row.X > df2.iloc[1].X1) and (row.Y < df2.iloc[1].Y1)
    return c1

    DF_NEW = DF1[DF1.apply(lambda x: isInSquare(x,DF2),axis = 1)]

    print DF_NEW

如何使用 Tkinter 中的按钮播放它? 这不起作用:

if __name__ == '__main__':
    root = Tk()

    root.title('title')
    root.geometry("450x150+200+200")

    x = (root.winfo_screenwidth() - root.winfo_reqwidth()) / 2
    y = (root.winfo_screenheight() - root.winfo_reqheight()) / 2
    root.geometry("+%d+%d" % (x, y))

    b1 = Button(root, text='txt', font=('arial', 12), command=isInSquare(row, df2))
    b1.pack(side=LEFT, padx=5, pady=5)
    root.mainloop()

我收到如下错误: NameError: name 'row' is not defined 否则我会离开command=isInSquare() 错误:TypeError: isInSquare() takes exactly 2 arguments (0 given) 任何人都可以在这方面提供帮助吗? df1 和 df2 是数据帧,所以我不能将值放在命令中,我不知道该怎么做;/

感谢您的建议

【问题讨论】:

  • 您需要在b2 = 行中定义row before
  • 如果他只定义 row 和 df2 它会在点击按钮后崩溃

标签: python function button tkinter callback


【解决方案1】:

这是因为您在初始化按钮时调用了函数 isInSquare,

b2 = Button(root, text='Convert', font=('arial', 12), command=isInSquare(row,df2))

你必须将一个函数传递给命令参数,所以不要对你传递的函数使用任何括号

编辑:

如果在您初始化按钮的地方可以使用 row 和 df2,您可以这样做

b2 = Button(root, text='Convert', font=('arial', 12), command=lambda: isInSquare(row,df2))

【讨论】:

  • 我不知道我是否理解正确,但是当我在没有任何括号的情况下给出command=isInSquare 时,我收到了同样的错误:TypeError: isInSquare() takes exactly 2 arguments (0 given)
  • 你必须设计不同,我不知道 row 和 df2 来自哪里,所以我不能具体告诉你,但是命令参数中的函数应该不带参数,做 def isInSquare() : ...不会崩溃。是的,你必须知道这些参数 row 和 df 来自哪里。
  • 我已经编辑了我的问题,也有 lambda: 选项相同的错误
  • 您说过“行仅在 isInSquare() 内部”,这不是真的,因为您将它作为参数传入,所以它来自外部,请在行中声明其声明“row = . ..”
  • hm 这部分代码已经写在这个话题里了:stackoverflow.com/questions/44456526/…,请快看,这一行只针对这一个定义,我不知道该怎么办了
猜你喜欢
  • 2013-02-21
  • 2021-08-27
  • 2021-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-11
  • 2013-11-10
相关资源
最近更新 更多