【问题标题】:How do I print dictionary length in tkinter output widget, not just in cmd如何在 tkinter 输出小部件中打印字典长度,而不仅仅是在 cmd
【发布时间】:2021-02-28 20:40:16
【问题描述】:

我已经成功创建了一个翻译应用程序,可以将英语单词翻译成我的母语。我创建了一个在 tkinter GUI 中打印出字典长度的按钮,但该按钮仅在 CMD 中打印结果;如何让它在我创建的输出小部件中打印出结果?下面是代码的摘录:

from tkinter import *
import tkinter. messagebox
root=Tk()
root.geometry('250x200')
root.title("Meta' Translator")
root.configure(background="#35424a")

def clk():
    print(len(exlist))

#heading
lab=Label(root,text='Translate English Words to Meta\'',font=('none 11 bold'))
lab.place(x=0,y=2)

#output label
lab=Text(root,width=5,height=1,font=('Times 18'),fg="black")
lab.place(x=59,y=70)

#print button
but=Button(root,padx=3,pady=3,text='Length',command=clk,bg='powder blue',font=('none 10 bold'))
but.place(x=0,y=70)


exlist={
    "abdomen":"fɨbûm", "abdomens":"tɨbûm",
    "adam's apple":"ɨ̀fɨ̀g ədɔ'", "adam's apples":"tɨ̀fɨ̀g ədɔ'",
    "ankle":"ɨgúm ǝwù"
    }

root.mainloop()

【问题讨论】:

  • 首先,为什么要为标签和文本小部件使​​用相同的变量名?其次,当您说“我创建的输出小部件”时,您是指标签还是文本小部件。两者都可以作为输出使用。
  • 对不起,这是一个错误;推荐“#output 标签”是#output 小部件。我应该为 lab2 下的变量命名。

标签: python dictionary tkinter


【解决方案1】:

您可以使用 insert() 方法更改 clk() 函数内部的 Text()-object 的文本:

def clk():
    lab.delete(1.0,"end") #delete the current content if there is some
    lab.insert(1.0, str(len(exlist)))

【讨论】:

  • 非常感谢!你刚刚解决了我的问题。成功了!
  • 顺便说一句,将1.0 放在引号中是惯例。此外,您无需调用 str - <tkinter.Text>.insert 可以采用所有内置类型。当小部件中没有任何内容时,它还约定在"end" 处插入文本。
  • @TheLizzard 大会?强烈建议使用float而不是str作为索引,因为float和str在四舍五入时含义不同。
  • @CoolCloud 浮点数被四舍五入,所以text.insert(1.1, "a") 变得与text.insert(1.10, "a") 相同。这就是为什么强烈建议您使用字符串而不是浮点数
  • @CoolCloud :D 文本小部件使​​用字符串。
【解决方案2】:
#THANKS JONAS FOR HELPING OUT!
from tkinter import *
import tkinter. messagebox
root=Tk()
root.geometry('250x200')
root.title("Meta' Translator")
root.configure(background="#35424a")

#Courtesy of Jonas
def clk():
    lab2.delete(1.0,"end") #delete the current content if there is some
    lab2.insert(1.0, str(len(exlist)))

#heading
lab=Label(root,text='Translate English Words to Meta\'',font=('none 11 bold'))
lab.place(x=0,y=2)

#output widget
lab2=Text(root,width=5,height=1,font=('Times 18'),fg="black")
lab2.place(x=59,y=70)

#print button
but=Button(root,padx=3,pady=3,text='Length',command=clk,bg='powder blue',font= 
('none 10 bold'))
but.place(x=0,y=70)


exlist={
    "abdomen":"fɨbûm", "abdomens":"tɨbûm",
    "adam's apple":"ɨ̀fɨ̀g ədɔ'", "adam's apples":"tɨ̀fɨ̀g ədɔ'",
    "ankle":"ɨgúm ǝwù"
    }

root.mainloop()

【讨论】:

  • 如果此代码来自另一个答案,则将其删除并将其标记为正确答案。
  • 新代码是我根据 Jonas 提供的解决方案所做的更正。
  • 如果乔纳斯解决方案给了你答案,那么接受它并删除它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-31
  • 2020-04-28
  • 2013-07-05
  • 2022-10-06
  • 2022-11-13
  • 1970-01-01
相关资源
最近更新 更多