龙空技术网

Tkinter中的单行文本输入框

面向对象思考 46

前言:

目前朋友们对“单行文本框使用什么标签表示”都比较关怀,大家都需要剖析一些“单行文本框使用什么标签表示”的相关知识。那么小编在网上网罗了一些关于“单行文本框使用什么标签表示””的相关文章,希望咱们能喜欢,你们快快来了解一下吧!

文本输入框是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(): print("INSERT=", entry.index(INSERT), 'ANCHOR=', entry.index(ANCHOR)) 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的用法。

完整代码可以从以下链接下载:

觉得本文有帮助?请分享给更多人。

关注【面向对象思考】,轻松学习每一天!

有任何疑问,欢迎留言提问或讨论。

面向对象设计,面向对象编程,面向对象思考!

标签: #单行文本框使用什么标签表示 #单行文本输入框