tkinter-如何仅绑定控件而不绑定control + key?

问题描述 投票:0回答:1

[在Python 3 Tkinter中,如何仅将控制键绑定到小部件而不是<control-key>?通常,还需要绑定另一个密钥。

python python-3.x tkinter bind key-bindings
1个回答
2
投票

您将必须绑定<Control_L><Control_R>

import tkinter as tk

def on_press(event):
    print(event)

root = tk.Tk()
root.bind('<Control_L>', on_press)
root.bind('<Control_R>', on_press)
root.mainloop()

最终,您可以使用每一个键都执行的<Key>,然后检查event.keysymevent.code

import tkinter as tk

def on_press(event):
    print(event)
    print(event.keysym in ('Control_L', 'Control_R'))
    print(event.keycode in (37, 105))

root = tk.Tk()
root.bind('<Key>', on_press)
root.mainloop()

-2
投票

使用出价时,有两种使用方式。您可以在命令后使用lambda。如果要将特定的键绑定到某个功能(如按回车键),则可以这样操作:

ent2 = Entry(top, show='*', bg='grey')
ent2.bind('<Return>', login)
ent2.pack()

点击返回将引导您进入功能。在上面的实例中,它将运行函数login

您也可以使用内置功能:

ex = Button(top, text='EXIT', command=root.quit)
ex.pack()

这将自动退出根目录,而无需单独的功能。还有其他内置功能。这是一些绑定和一个简单的tkinter登录屏幕的示例:

from tkinter import *
from PIL import ImageTk, Image

root = Tk()
root.withdraw()


def login(event):
    if ent1.get() == 'admin' and ent2.get() == 'password':
        root.iconify()
        top.destroy()


def client_data(event):
    root.withdraw()
    top = Toplevel()
    top.title('Client Data')
    top.geometry('800x500')
    top.configure(background='grey')
    client1 = Message(top, text='Random skeleton', bg='grey', width=350)
    client1.pack()
    x = Button(top, text='Close', bg='red', command=top.destroy)
    root.iconify()
    x.pack()


image1 = ImageTk.PhotoImage(Image.open('ileye.png'))
top = Toplevel()
top.title('Login')
top.configure(background='grey')
photo = Label(top, image=image1)
photo.pack()
user = Label(top, text='User name', bg='grey')
user.pack()
ent1 = Entry(top, bg='grey')
ent1.pack()
pwd = Label(top, text='Password', bg='grey')
pwd.pack()
ent2 = Entry(top, show='*', bg='grey')
ent2.bind('<Return>', login)
ent2.pack()
ex = Button(top, text='EXIT', command=root.quit)
ex.pack()
check = Checkbutton(top, text='Remember me', bg='grey')
check.pack()


root.title('Main Screen')
root.attributes('-zoomed', True)
menu_drop = Menu(root)
root.config(menu=menu_drop)
file = Menu(menu_drop)
menu_drop.add_cascade(label='Options', menu=file)
file.add_command(label='New', command=root.quit)  ## New Function
client = Button(root, text='Client list')
file.add_separator()
file.add_command(label='Close App', command=root.quit)
client.bind('<Button-1>', client_data)
client.pack()
exi = Button(root, text='EXIT', command=root.quit)
exi.pack()


root.mainloop()
© www.soinside.com 2019 - 2024. All rights reserved.