Tkinter程序在启动时运行按钮命令吗? [英] Tkinter program runs button command on startup?

查看:47
本文介绍了Tkinter程序在启动时运行按钮命令吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个程序,该程序基本上应该具有一个按钮,该按钮可以打开(用户名)文件夹中的文件对话框.但是,当我运行该程序时,它甚至不按按钮就可以打开.而且,该按钮甚至不会显示.因此,除了这个问题之外,我还必须找到一种将所选目录转换为字符串的方法.

So I have a program that is basically supposed to have a button that opens a file dialog in the (username) folder. But when I run the program it opens without even pushing the button. What's more, the button doesn't even show up. So in addition to that problem I have to find a way to turn the selected directory into a string.

import tkinter
import tkinter.filedialog
import getpass
gui = tkinter.Tk()
user = getpass.getuser()
tkinter.Button(gui, command=tkinter.filedialog.askopenfilename(initialdir='C:/Users/%s' % user)).pack()
gui.mainloop()

推荐答案

关于第一个问题,您需要将对 tkinter.filedialog.askopenfilename 的调用放在一个函数中,以使其不会在启动时运行.我实际上今天早上刚刚回答了一个问题,所以您可以查看

Regarding your first issue, you need to put the call to tkinter.filedialog.askopenfilename in a function so that it isn't run on startup. I actually just answered a question about this this morning, so you can look here for the answer.

关于第二个问题,该按钮未显示,因为您从未将其放置在窗口中.您可以为此使用 grid 方法:

Regarding your second issue, the button isn't showing up because you never placed it on the window. You can use the grid method for this:

button = tkinter.Button(gui, command=lambda: tkinter.filedialog.askopenfilename(initialdir='C:/Users/%s' % user))
button.grid()

总而言之,您的代码应如下所示:

All in all, your code should be like this:

import tkinter
import tkinter.filedialog
import getpass
gui = tkinter.Tk()
user = getpass.getuser()
button = tkinter.Button(gui, command=lambda: tkinter.filedialog.askopenfilename(initialdir='C:/Users/%s' % user))
button.grid()
gui.mainloop()

这篇关于Tkinter程序在启动时运行按钮命令吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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