import random
import string
import tkinter.messagebox
from tkinter import *
from tkinter import ttk
import tkinter as tk
password = 0
window = tk.Tk()
def Manager():
while True:
def random_password():
# get random password
characters = string.ascii_letters + string.digits
global password
password = ''.join(random.choice(characters) for i in range(8))
def Button():
label = tkinter.Label(
text=password,
foreground="white", # Set the text color to white
background="black", # Set the background color to black
width = 20,
)
button = tk.Button(
text='Agian?',
width = 20,
bg="blue",
fg="yellow",
command=lambda:[window.destroy(), Manager()]
)
label.pack()
button.pack()
window.mainloop()
random_password()
Button()
Manager()
我想每次按下按钮都得到一个新密码。这是我的错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:UsersoksraAppDataLocalProgramsPythonPython39libtkinter__init__.py", line 1892, in __call__
return self.func(*args)
File "C:UsersoksraPycharmProjectspythonProject1main.py", line 33, in <lambda>
command=lambda:[window.destroy(), Manager()]
File "C:UsersoksraAppDataLocalProgramsPythonPython39libtkinter__init__.py", line 2312, in destroy
self.tk.call('destroy', self._w)
_tkinter.TclError: can't invoke "destroy" command: application has been destroyed
我该如何修复它?
您没有在函数中创建Tk()
的实例。将Tk()
的实例放在函数中,它将工作。您还应该考虑将导入语句更改为仅import tkinter as tk
,然后始终使用该名称空间以保持一致性。应该避免使用通配符import
。我做了以下更改,现在应该可以为您工作了。您可能会受益于将其重组为class
而不是像您那样嵌套函数。
import random
import string
import tkinter.messagebox
from tkinter import ttk
import tkinter as tk
password = 0
def Manager():
window = tk.Tk()
while True:
def random_password():
# get random password
characters = string.ascii_letters + string.digits
global password
password = ''.join(random.choice(characters) for i in range(8))
def Button():
label = tk.Label(
text=password,
foreground="white", # Set the text color to white
background="black", # Set the background color to black
width = 20,
)
button = tk.Button(
text='Agian?',
width = 20,
bg="blue",
fg="yellow",
command=lambda:[window.destroy(), Manager()]
)
label.pack()
button.pack()
window.mainloop()
random_password()
Button()
Manager()
考虑一下,如果你只改变标签,而不是破坏和创建一个新的窗口,这是多么容易。
import random
import string
import tkinter.messagebox
from tkinter import ttk
import tkinter as tk
def generate_password():
characters = string.ascii_letters + string.digits
global password
password = ''.join(random.choice(characters) for i in range(8))
label['text'] = password
window = tk.Tk()
label = tk.Label(window, text="", foreground="white", background="black",
width=20)
label.pack()
button = tk.Button(window, text="Generate Password", bg="blue", fg="yellow", width=20,
command=generate_password)
button.pack()
window.mainloop()