[英]Copy a label on tkinter and change the text on button click?
I have some program of this kind of type:我有一些这种类型的程序:
from tkinter import *
def apply_text(lbl_control):
lbl_control['text'] = "This is some test!"
master = Tk()
lbl = Label(master)
btn = Button(master, text="apply", command=lambda: apply_text(lbl))
lbl.pack()
btn.pack()
mainloop()
My aim now is to copy the text of the label lbl
itself without any ability to change it.我现在的目标是复制 label
lbl
本身的文本,而不能更改它。 I tried the following way to solve the problem:我尝试了以下方法来解决问题:
from tkinter import *
def apply_text(lbl_control):
lbl_control.insert(0, "This is some test!")
master = Tk()
lbl = Entry(master, state="readonly")
btn = Button(master, text="apply", command=lambda: apply_text(lbl))
lbl.pack()
btn.pack()
mainloop()
because of state = "readonly"
it is not possible to change the text insert of lbl
anymore.因为
state = "readonly"
不可能再更改lbl
的文本插入。 For that reason nothing happens if I click on the button apply
.出于这个原因,如果我点击按钮
apply
什么也不会发生。 How can I change it?我该如何改变它?
There is a simple way to do that simple first change the state
of entry to normal
, Then insert the text, and then change the state
back to readonly
.有一个简单的方法可以做到,简单的先把entry的
state
normal
,然后插入文本再把state
改回readonly
。
from tkinter import *
def apply_text(lbl_control):
lbl_control['state'] = 'normal'
lbl_control.delete(0,'end')
lbl_control.insert(0, "This is some test!")
lbl_control['state'] = 'readonly'
master = Tk()
lbl = Entry(master, state="readonly")
btn = Button(master, text="apply", command=lambda: apply_text(lbl))
lbl.pack()
btn.pack()
mainloop()
There is another way to do this using textvariable
.还有另一种方法可以使用
textvariable
来做到这一点。
Code: (Suggested)代码:(建议)
from tkinter import *
def apply_text(lbl_control):
eText.set("This is some test.")
master = Tk()
eText = StringVar()
lbl = Entry(master, state="readonly",textvariable=eText)
btn = Button(master, text="apply", command=lambda: apply_text(lbl))
lbl.pack()
btn.pack()
mainloop()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.