【问题标题】:Change the label text, Tkinter更改标签文本,Tkinter
【发布时间】:2021-02-17 09:28:28
【问题描述】:

这是我的代码 sn-p:

def message(name, button):
    button['state'] = DISABLED
    mgs_label = ttk.Label(root)

   if button["text"] == "Encryption":

       mgs_label.pack_forget()
       mgs = encryption(name)
       mgs_label = ttk.Label(root, text=mgs).pack(side=LEFT)

   if button["text"] == "Decryption":

      mgs_label.pack_forget()
      mgs = decryption(name)
      mgs_label = ttk.Label(root, text=mgs).pack(side=LEFT)

当我单击按钮时,无论是加密按钮还是解密按钮,它都会出现在提到的位置。 这是快照: image1

当我单击另一个按钮时,文本出现在前一个按钮之后,我想删除以前的文本,然后应该显示最后的 mgs。

第二张快照:image2

即使我尝试创建全局变量,但问题是加密或解密已完成,但 GUI 上未显示 mgs 这是代码:

encryption_label = ttk.Label(root)
decryption_label = ttk.Label(root)
def message(name, button):
    button['state'] = DISABLED
    global encryption_label, decryption_label
    if button["text"] == "Encryption":

       if decryption_label.winfo_exists():
          decryption_label.pack_forget()

       mgs = encryption(name)
       encryption_label["text"] = mgs
       encryption_label.pack(side=LEFT)

    if button["text"] == "Decryption":

       if encryption_label.winfo_exists():
          encryption_label.pack_forget()

    mgs = decryption(name)
    decryption_label["text"] = mgs
    decryption_label.pack(side=LEFT)

【问题讨论】:

  • 尝试为EncryptionDecryption 状态使用不同的标签变量
  • @crackanddie 我尝试并相应地编辑了问题,但仍然无法正常工作。
  • @HimanshuGurjar 第二种方法更好,但您的缩进似乎不对。由于在第二种方法中,您使用了两个标签,因此无需在每次调用 message 时设置文本,而是在声明本身 encryption_label = ttk.Label(root, text='Successfull encrypted') 中设置文本,类似于解密。但更好的方法是声明标签的单个全局实例并更新文本。
  • 您的第一种方法将不起作用,因为您每次调用消息时都会创建标签的新实例,因此使用mgs_label.pack_forget() 将永远不会隐藏以前的标签。另外,在mgs_label = ttk.Label(root, text=mgs).pack(side=LEFT) msg_labelNone pack 返回None
  • @JacksonPro 是的,现在我明白了,感谢您的建议。但即使使用单个全局标签变量也无法正常工作,我只是在调用函数处创建了一个标签并将其作为参数传递给被调用函数,然后进行配置。

标签: python tkinter label


【解决方案1】:

我建议只创建一次标签并使用 label.configure 更改文本。 您应该提供一个工作示例而不是代码 sn-p。我为你做了一个。 谢谢你的提问。

import tkinter as tk
from tkinter import ttk
def e():
    message(None,x_button)
def d():
    message(None,y_button)
def message(name, button):
    #button['state'] = tk.DISABLED

    if button["text"] == "Encryption":
        mgs_label.configure(text = 'encrypted stuff')

    if button["text"] == "Decryption":
        mgs_label.configure(text = 'decrypted stuff')
  
root = tk.Tk()
x_button = tk.Button(root,text = 'Encryption',
                     command = e)
y_button = tk.Button(root,text = 'Decryption',
                    command = d )
mgs_label = ttk.Label(root)
y_button.pack()
x_button.pack()    
mgs_label.pack()
root.mainloop()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多