本小节实现右键的粘贴、复制、截切功能
代码
def cut(editor):
editor.event_generate("<>" )
def copy(editor):
editor.event_generate("<>" )
def paste(editor):
editor.event_generate('<>' )
def rightKey(widget, event, editor):
"""功能:cut copy paste"""
menu_bar = tk.Menu(widget, tearoff=False)
menu_bar.delete(0, tk.END)
menu_bar.add_command(label='剪切', command=lambda: cut(editor))
menu_bar.add_command(label='复制', command=lambda: copy(editor))
menu_bar.add_command(label='粘贴', command=lambda: paste(editor))
menu_bar.post(event.x_root, event.y_root)
def menuRK(root, widget):
"""部件添加右键功能"""
widget.bind("" , lambda x: rightKey(root, x, widget))
其余功能可以自行加入代码中,例如加入保存功能
def save(widget):
file_path = filedialog.asksaveasfilename(title=u'保存文件')
content = widget.get('1.0', tk.END)
if file_path is not None:
with open(file=file_path, mode='w', encoding='utf-8') as file:
file.write(content)
def rightKey(widget, event, editor):
menu_bar = tk.Menu(widget, tearoff=False)
menu_bar.add_command(label='保存', command=lambda: save(editor))
回车键的功能大部分是具有确定的功效
代码
def enterKey(widget, mapping):
widget.bind("" , lambda x: mapping(widget))
案例
def getValue(widget):
print(widget.get('1.0', tkinter.END))
text = tkinter.Text(tkinter.TK())
text.pack()
enterKey(text, getValue)
隐藏或显示组件
代码
def hideOrDisplay(widgets, status='hide'):
if status.lower() == 'hide':
widgets.pack_forget()
elif status.lower() == 'display':
widgets.pack()
制作进度条的效果
代码
def progressBar(widget):
sub_win = tkinter.Toplevel(widget)
sub_win.title("下载")
sub_win.geometry('420x20+100+30')
canvas = tkinter.Canvas(sub_win, width=280, height=10, bg="blue")
canvas.pack()
fill_line = canvas.create_rectangle(2, 2, 0, 10, fill="green")
for n in range(280):
n += 1
canvas.coords(fill_line, (0, 0, n, 10))
sub_win.update()
time.sleep(0.2)