我正在编写一个python脚本,要求用户输入文件夹的名称。对于大多数情况,默认就足够了,但我想要一个允许用户覆盖默认值的输入框。这就是我所拥有的:
from Tkinter import *
import time
def main():
#some stuff
def getFolderName():
master = Tk()
folderName = Entry(master)
folderName.pack()
folderName.insert(END, 'dat' + time.strftime('%m%d%Y'))
folderName.focus_set()
createDirectoryName = folderName.get()
def callback():
global createDirectoryName
createDirectoryName = folderName.get()
return
b = Button(master, text="OK and Close", width=10, command=callback)
b.pack()
mainloop()
return createDirectoryName
getFolderName()
#other stuff happens....
return
if __name__ == '__main__':
main()
我对tkInter几乎一无所知,并且有两个问题。
global createDirectoryName
覆盖默认条目是最好的方法吗?按下按钮时,如何使按钮关闭窗口。 我试过了
def callback():
global createDirectoryName
createDirectoryName = folderName.get()
master.destroy
但这只会在运行脚本时破坏窗口。
答案 0 :(得分:0)
我不知道你在Tkinter有多经验,但我建议你上课。
try:
from tkinter import * #3.x
except:
from Tkinter import * #2.x
class anynamehere(Tk): #you can make the class inherit from Tk directly,
def __init__(self): #__init__ is a special methoed that gets called anytime the class does
Tk.__init__(self) #it has to be called __init__
#further code here e.g.
self.frame = Frame()
self.frame.pack()
self.makeUI()
self.number = 0 # this will work in the class anywhere so you don't need global all the time
def makeUI(self):
#code to make the UI
self.number = 1 # no need for global
#answer to question No.2
Button(frame, command = self.destroy).pack()
anyname = anynamehere() #remember it alredy has Tk
anyname.mainloop()
另外,为什么要覆盖deafult Entry行为? 解决方案是创建另一个按钮并将命令绑定到它
self.enteredtext = StringVar()
self.entry = Entry(frame, textvariable = self.enteredtext)
self.entry.pack()
self.button = Button(frame, text = "Submit", command = self.getfolder, #someother options, check tkitner documentation for full list)
self.button.pack()
def getfolder(self): #make the UI in one method, command in other I suggest
text = self.enteredtext.get()
#text now has whats been entered to the entry, do what you need to with it