我正在玩python,需要在按下按钮后清除条目小部件, 我在使小部件全局化方面遇到了问题?
这里是我的代码
#!/usr/bin/python3
from tkinter import *
from tkinter import ttk
root = Tk()
usernameVal = StringVar()
def submitForm(*args):
try:
print("submitForm pressed")
print('name is %s' % usernameVal.get()) #mira como hace el print!
#usernameVal.clear(1.0, END) ??
except ValueError:
pass
def main():
#container view
mainframe = ttk.Frame(root, padding="3 3 12 12") # mainframe contained by root!, init
mainframe.grid(column=0, row=0, sticky=(N, W, E, S)) # add subview mainframe
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)
#UI widgets
createLbl = ttk.Label(mainframe, text='Create login & Password')
createLbl.grid(column=2 , row=1, sticky=(W,E))
# user name
nameLbl = ttk.Label(mainframe, text='User Name')
nameLbl.grid(column=1 , row=2, sticky=(W,E))
#usernameVal = StringVar()
usernameTf = ttk.Entry(mainframe, textvariable = usernameVal)
usernameTf.grid(column=2 , row=2, sticky=(W,E))
button = ttk.Button(mainframe, text='Create User', command=submitForm)
button.grid(column=3 , row=2, sticky=(W,E))
#my loop
root.mainloop()
if __name__ == "__main__": main()
那么如何清除textField呢,这也是从入口小部件中获取文本的好方法吗? 谢谢!
答案 0 :(得分:4)
我已经在这里更改了一些代码&根据我的编码风格。但你会得到它的要点
from Tkinter import *
from Tkinter import Tk
root = Tk()
usernameVal = StringVar()
class myclass():
def __init__(self):
self.main()
def submitForm(self,*args):
try:
print("submitForm pressed")
print('name is %s' % self.usernameVal.get()) #mira como hace el print!
self.usernameVal.set("")
#usernameVal.clear(1.0, END) ??
except ValueError:
pass
def main(self):
#container view
mainframe = Frame(root) # mainframe contained by root!, init
mainframe.grid(column=0, row=0, sticky=(N, W, E, S)) # add subview mainframe
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)
#UI widgets
createLbl = Label(mainframe, text='Create login & Password')
createLbl.grid(column=2 , row=1, sticky=(W,E))
# user name
nameLbl = Label(mainframe, text='User Name')
nameLbl.grid(column=1 , row=2, sticky=(W,E))
self.usernameVal = StringVar()
usernameTf = Entry(mainframe, textvariable = self.usernameVal)
usernameTf.grid(column=2 , row=2, sticky=(W,E))
button = Button(mainframe, text='Create User', command=self.submitForm)
button.grid(column=3 , row=2, sticky=(W,E))
#my loop
root.mainloop()
if __name__ == "__main__":
myclass()
我所做的基本上是创建了一个班级&使用self运算符。为了获得用户输入的价值,我使用了self.usernameVal.get
&清除它我已经使用self.usernameVal.set=''
。