Python Tkinter - 用按钮传递值 [英] Python Tkinter - Passing values with a button

查看:39
本文介绍了Python Tkinter - 用按钮传递值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过按钮将参数传递给函数?

How do I pass parameters to a function through a button?

variable = str()

def RandomFunction(variable): 
    print (variable) 

EntryBox = Entry(MainWindow, textvariable = variable).pack() 
FunctionCall = Button(MainWindow, text="Enter", command=RandomFunction(variable)) 

当按下按钮时,它似乎没有打印任何内容.我四处搜索,似乎使用 lambda 可以修复它并允许(变量)传递给函数,但是在尝试了 lambda variable:variable 之后我仍然可以不让它工作.

It seems like it just doesnt print anything when the button is pressed. I've searched around and it seems that using lambda can fix it and allow (variable) to be passed to the function but after experimenting with lambda variable:variable I still can't get it to work.

推荐答案

这里的其他答案是有效的,但就像生活中的很多事情一样,有不止一种方法可以做你想做的事.

The other answers here work, but like a lot of things in life, there's more than one way to do what you're trying to do.

您问题中的代码实际上混合了几种从 Entry 小部件获取数据的方法.您正在使用 textvariable 和 lambda,但您只需要一个.似乎已经涵盖了 lambda,所以这里有一个关于 textvariable 的快速答案:

The code in your question actually mixes a couple of methods of getting data from the Entry widget. You're using textvariable and lambda, but you only need one. It seems like lambda has been covered, so here's a quick answer about textvariable:

首先,您需要像这样将变量设为 Tkinter 字符串类型:

First, you need to make your variable of a Tkinter string type like this:

variable = StringVar()

您的输入小部件很好,它已连接到 StringVar().不过,您的按钮不需要 lambda,因为您不需要将参数传递给 RandomFunction().

Your entry widget is fine, it's connected to the StringVar(). Your button doesn't need lambda, though, because you don't need to pass an argument to your RandomFunction().

FunctionCall = Button(MainWindow, text='Enter', command=RandomFunction).pack()

最后,您的函数需要稍微修改一下,因为它不再接受参数,它只是在调用 StringVar() 时使用 .get() 方法:

Lastly, your function needs a little rework, because it's not taking an argument anymore, it's just going to use the .get() method on your StringVar() whenever it's called:

def RandomFunction():
    print(variable.get())

您可以在此处阅读有关 StringVar() 的更多信息:http://effbot.org/tkinterbook/variable.htm

You can read more about StringVar()s here: http://effbot.org/tkinterbook/variable.htm

这篇关于Python Tkinter - 用按钮传递值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆