[英]refresh the Label Tkinter?
I want to refresh the the password Label every time the refresh button is pressed.每次按下刷新按钮时,我都想刷新密码标签。 I tried the
.config
but it doesn't work.我尝试了
.config
但它不起作用。
import random
import string
import tkinter.messagebox
from tkinter import *
def get_all_passwords():
with open('Passwords.txt') as f:
global password_Text
password_Text = f.read()
f.close()
def main_window():
def all_passwords_text():
global password_Text
All_passwords_label.config(text=password_Text)
All_passwords_label = tkinter.Label(
window,
text=password_Text,
foreground="black",
background="white",
width=25,
)
password_label = tkinter.Label(
text=password,
foreground="white",
background="black",
width=20,
)
save_button = tk.Button(
text='save',
width=10,
cursor='hand1',
bg='light gray',
command=lambda:[write_password_to_txt(), All_passwords_label, window.update()]
)
refresh_button = tk.Button(
text='Refresh',
width=20,
bg="white",
fg="black",
command=all_passwords_text
)
All_passwords_label.pack(side='right')
password_label.pack()
safe_entry.pack()
save_button.pack()
refresh_button.pack()
window.mainloop()
random_password()
main_window()
import tkinter as tk # avoid star imports; this can lead to namespace pollution
import tkinter.messagebox
# other imports, etc.
# declare a StringVar to store the label text
password_var = tk.StringVar()
def get_all_passwords():
with open('Passwords.txt') as f:
password_Text = f.read()
password_var.set(password_text) # update 'password_var'
# f.close() - you don't need this when using 'with'
# see link below
"Context Managers and Python's with Statement" “上下文管理器和 Python 的 with 语句”
# add a 'textvariable' binding to your label
# the label text will update whenever the variable is set
All_passwords_label = tk.Label(
window,
text=password_Text,
textvariable=password_var # add this!
foreground="black",
background="white",
width=25,
)
Now any time you call get_all_passwords()
the label text of All_passwords_label
should update.现在,任何时候您调用
get_all_passwords()
, All_passwords_label
的标签文本都应该更新。 Note that you no longer need the all_passwords_text
function at all, and you don't need to use globals either.请注意,您根本不再需要
all_passwords_text
函数,也不需要使用全局变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.