简体   繁体   English

Python:Tkinter中的按钮小部件

[英]Python: Button widget in Tkinter

I have just now begun with GUI programming in Python 2.7 with Tkinter. 我刚刚开始使用Tkinter在Python 2.7中进行GUI编程。

I want to have a button Browse , which when clicked opens the Windows File Explorer and returns the path of file selected to a variable. 我想要一个浏览按钮,单击该按钮将打开Windows File Explorer,并将所选文件的路径返回到变量。 I wish to use that path later. 我希望以后再使用该路径。

I am following the code given here . 我正在遵循此处给出的代码。 It outputs a window displaying 5 buttons, but the buttons do nothing. 它输出一个显示5个按钮的窗口,但是这些按钮什么也不做。 On clicking the first button, it doesn't open the selected file. 单击第一个按钮时,它不会打开所选文件。

Likewise, on clicking the second button, the askopenfilename(self) function is called and it should return a filename. 同样,在单击第二个按钮时,将askopenfilename(self)函数,并且该函数应返回文件名。 Like I mentioned, I need that filename later. 就像我提到的那样,以后我需要该文件名。

How to I get the value returned by the function into some variable for future use? 如何将函数返回的值转换为某些变量以备将来使用?

There is no point in using return inside a callback to a button. 在按钮的回调中使用return毫无意义。 It won't return to anywhere. 它不会返回任何地方。 The way to make a callback save data is to store it in a global variable, or an instance variable if you use classes. 进行回调保存数据的方法是将其存储在全局变量中,如果使用类,则将其存储在实例变量中。

def fetchpath():
    global filename
    filename = tkFileDialog.askopenfilename(initialdir = 'E:')

FWIW (and unrelated to the question): you're making a very common mistake. FWIW(与问题无关):您犯了一个非常常见的错误。 In python, when you do foo=bar().baz() , foo takes the value in baz() . 在python中,当您执行foo=bar().baz()foo将使用baz()的值。 Thus, when you do this: 因此,当您这样做时:

button = Button(...).pack()

button will take the value of pack() which always returns None . button将使用pack()的值,该值始终返回None You should separate widget creation from widget layout if you expect to save an actual reference to the widget being created. 如果希望保存对正在创建的小部件的实际引用,则应将小部件的创建与小部件的布局分开。 Even if you're not, it's a good practice to separate the two. 即使您不是,将两者分开也是一个好习惯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM