在 Tkinter 中通过绑定 Button 和 ButtonRelease 显示和隐藏密码?

发布于 2025-01-11 23:43:57 字数 769 浏览 2 评论 0原文

我正在学习Python3和tkinter。我试图使用绑定

这是我的代码:

import tkinter as tk

def show(e):
    passwd_entry.config(show="")
# def hide(event):
#     passwd_entry.config(show="*")
root = tk.Tk()

passwd_entry = tk.Entry(root, show='*', width=20)
passwd_entry.pack(side=tk.LEFT)

toggle_btn = tk.Button(root, text='Show Password', width=15, command=show)
toggle_btn.pack(side=tk.LEFT)
toggle_btn.bind("<Button>", show)
# toggle_btn.bind("<ButtonRelease>", hide)

root.mainloop()

这是我单击 button 时的错误:

TypeError: show() missing 1 required positional argument: 'e'

I'm learning Python3 and tkinter. I was trying to show password with binding <Button> and hide password with binding <ButtonRelease>, but I didn't have any solution. All I can do is to show the password, then the error occurred:

Here is my code:

import tkinter as tk

def show(e):
    passwd_entry.config(show="")
# def hide(event):
#     passwd_entry.config(show="*")
root = tk.Tk()

passwd_entry = tk.Entry(root, show='*', width=20)
passwd_entry.pack(side=tk.LEFT)

toggle_btn = tk.Button(root, text='Show Password', width=15, command=show)
toggle_btn.pack(side=tk.LEFT)
toggle_btn.bind("<Button>", show)
# toggle_btn.bind("<ButtonRelease>", hide)

root.mainloop()

This is the error when I click button:

TypeError: show() missing 1 required positional argument: 'e'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

恬淡成诗 2025-01-18 23:43:57

tkinter 实例创建需要在您要调用的函数定义事件之前发生。

还可以使用 lambda 函数调用 bind 中的 show 函数,如下面的代码所示。应该有帮助。

import tkinter as tk

root = tk.Tk()

def show():
    passwd_entry.config(show="")
def hide():
    passwd_entry.config(show="*")

passwd_entry = tk.Entry(root, show='*', width=20)
passwd_entry.pack(side=tk.LEFT)

toggle_btn = tk.Button(root, text='Show Password', width=15)
toggle_btn.pack(side=tk.LEFT)
toggle_btn.bind("<ButtonPress>", lambda event:show())
toggle_btn.bind("<ButtonRelease>", lambda event:hide())

root.mainloop()

The tkinter instance creation needs to happen before the function definition event which you want to call.

Also use the lambda function to call the show function inside bind as mentioned in below code. It should help.

import tkinter as tk

root = tk.Tk()

def show():
    passwd_entry.config(show="")
def hide():
    passwd_entry.config(show="*")

passwd_entry = tk.Entry(root, show='*', width=20)
passwd_entry.pack(side=tk.LEFT)

toggle_btn = tk.Button(root, text='Show Password', width=15)
toggle_btn.pack(side=tk.LEFT)
toggle_btn.bind("<ButtonPress>", lambda event:show())
toggle_btn.bind("<ButtonRelease>", lambda event:hide())

root.mainloop()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文