Tkinter中如何创建和使用单行文本输入框,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
文本输入框是GUI编程中最常用的输入形式,Tkinter为此提供了Entry类。先看程序执行结果:
首先是构建Entry对象,同样的手法,差不多的结果。
# create fontftTimes = Font(family='Times', size=24, weight=BOLD)# create a label to change state.entry = Entry(root, background="#a0ffa0",foreground="#000000", disabledbackground="#7f7f7f",disabledforeground="#000000", font=ftTimes, width=32)entry.grid(row=0, column=0, columnspan=2)
接下来构建一个多行标签对象处理表示键盘事件:
# create text variable.str_var = StringVar()# create a label to change state.label = Label(root,height=10, justify=LEFT, textvariable=str_var)label.grid(row=1, column=0, columnspan=2)
接下来为Entry对象绑定按键按下事件。代码的内容是将事件的信息转换为文字列再设置到前面构建的多行标签上。
# bind eventdef OnKeyPress(e): print(e) current = str_var.get() if len(current): str_var.set(current + '\n' + str(e)) else: str_var.set(str(e))entry.bind('<KeyPress>', OnKeyPress)
同样的转换状态按钮:
# change state function.def change_state(): state = entry.cget('state') if state=='disabled': entry.config(state='normal') elif state=='normal': entry.config(state='readonly') else: entry.config(state='disabled')# change state button.Button(root,text="State", command=change_state).grid(row=2, column=0, sticky=E+W)
删除选择文本的代码信息量比较大,稍微详细一点说明。
# delete selection.def delete_selection(): anchor = entry.index(ANCHOR) if anchor: # there is a selection # current position of the insertion cursor insert = entry.index(INSERT) sel_from = min(anchor, insert) sel_to = max(anchor, insert) # delete the selection. entry.delete(sel_from, sel_to)# delete selection button.Button(root,text="Delete", command=delete_selection).grid(row=2, column=1, sticky=E+W)
ANCHOR是表示选择文字开始位置的常数,有了这个常数我们就可以使用index方法取得第一个被选字符的索引;INSERT是表示插入光标位置的常数,利用这个常数,我们可以使用index方法取得光标位置的索引。当用户如下选择的时候:
被选文字的开始索引为1,光标位置的索引为6。用户也可能这样选:
这时被选文字的开始索引为6,光标位置的索引为1。
无论哪种情况,我们都可以删除从两个值的最小值开始到最大值范围的内容以实现选择文字的删除。当然了实际上你只要按一下delete键就可以完成同样的功能,这里只是为了展示Entry的用法。
关于Tkinter中如何创建和使用单行文本输入框问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://my.oschina.net/u/4579737/blog/4585453