问题描述
我有一个 tkinter 输入框,用户可以在其中插入目录的路径.或者,用户可以单击按钮来选择目录.如何设置按钮的输出以填充输入框?我尝试了以下操作,但 dirname
不是全局变量,因此 UserFileInput
无法识别.另外如何绑定输入字段旁边的按钮.
I have a tkinter Entry box in which the user can insert a path to the directory. Alternatively the user can click a button to select the directory. How can I set the output from the button to fill the Entry box? I have tried the following but dirname
is not a global variable and so is not recognised by UserFileInput
. Also how can I bind the button next to the entry field.
from Tkinter import *
import tkFileDialog
def askdirectory():
dirname = tkFileDialog.askdirectory()
return dirname
def UserFileInput(status,name):
optionFrame = Frame(root)
optionLabel = Label(optionFrame)
optionLabel["text"] = name
optionLabel.pack(side=LEFT)
text = str(dirname) if dirname else status
var = StringVar(root)
var.set(text)
w = Entry(optionFrame, textvariable= var)
w.pack(side = LEFT)
optionFrame.pack()
return w
if __name__ == '__main__':
root = Tk()
dirBut = Button(root, text='askdirectory', command = askdirectory)
dirBut.pack(side = RIGHT)
directory = UserFileInput("", "Directory")
root.mainloop()
推荐答案
你的 UserFileInput
应该返回 var
,而不是 w
.然后你可以在你的 askdirectory
函数中使用 var.set(dirname)
,它不需要返回任何东西.
Your UserFileInput
should return var
, not w
. Then you can use var.set(dirname)
in your askdirectory
function which doesn't have to return anything.
但是我不确定您尝试使用 text = str(dirname) if dirname else status
实现什么.为什么不直接使用 text = status
因为 dirname
还不能在那里定义?
I'm not sure however what you try to achieve with text = str(dirname) if dirname else status
. Why not just use text = status
since dirname
can't yet be defined there?
这应该按照您希望的方式工作.打印输入文本"按钮显示您可以检索输入框中的任何内容,可以是用户编写的,也可以是代码输入的.
This should work the way you want it to. The 'print entry text' button shows that you can retreive whatever is in the entry box, either written by the user or put there by the code.
from Tkinter import *
import tkFileDialog
def askdirectory():
dirname = tkFileDialog.askdirectory()
if dirname:
var.set(dirname)
def UserFileInput(status,name):
optionFrame = Frame(root)
optionLabel = Label(optionFrame)
optionLabel["text"] = name
optionLabel.pack(side=LEFT)
text = status
var = StringVar(root)
var.set(text)
w = Entry(optionFrame, textvariable= var)
w.pack(side = LEFT)
optionFrame.pack()
return w, var
def Print_entry():
print var.get()
if __name__ == '__main__':
root = Tk()
dirBut = Button(root, text='askdirectory', command = askdirectory)
dirBut.pack(side = RIGHT)
getBut = Button(root, text='print entry text', command = Print_entry)
getBut.pack(side = BOTTOM)
w, var = UserFileInput("", "Directory")
root.mainloop()
这篇关于如何使用 tkFileDialog.askdirectory 的输出来填充 tkinter 输入框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!