如何解决如何使用y滚动条在标签小部件中多行显示长字符串段落? tkinter
嘿,我试图将包含几个段落的文本放在标签小部件中。我希望它显示在多行上并使用y滚动条,以便所有内容都可以容纳并在标签小部件中查看。
结果应该是这样的: Except instead of a text widget it would be a label widget
我尝试使用以下代码进行此操作:
from tkinter import *
writtenSolution = Tk()
writtenSolution.title("Written Response Question")
writtenSolution.resizable(0,0)
header = LabelFrame(writtenSolution,bg="white")
content = LabelFrame(writtenSolution,bg="white")
header.columnconfigure(0,weight=1) # Forces column to expand to fill all available space
homeButton=Button(content,width=50,height=50)
try:
homeIcon=PhotoImage(file="yes.png")
homeButton.config(image=homeIcon)
homeButton.image = homeIcon
except TclError:
print("Home")
homeButton.grid(row=1,sticky="w",padx=15,pady=2)
titleHeader = Label(content,text="Solution Image here",pady=15,padx=20,bg="white",font=("Ariel",20,"bold"),anchor="w",relief="solid",borderwidth=1)
titleHeader.grid(row=2,column=0,columnspan=3,pady=5,ipadx=400,ipady=150)
text=str("CRXdJdRpVPJKzs2HZ 5YadBSDgsmMrWb OTsTkHoy23ygHrryEwNGvkabnM3UOJnM0PVvVU6KiXtDbvljdILbfwko1 R3dKSz6iTbKQHlHYqtFMB4xBclX5Jgc9Q8ThoXX292SO8JzWxaLq6jyfXItZx4g2 JQtAOaEtc4jSx643aLaqeRdyoqqvT1mzsrE5pa8EXMozajbRp5DvGpVanvym1BZFcdLmZEu1ykHgAGL4luFQYdoHTJ033Q3Btuu4oqRdAo4zAdPWVKOLGd316w7Os3H26eB2qQXxyMOfgzMWjWZD")
#the label widget is below:
answerInput = Label(content,borderwidth=2,font=("HelvLight",18),height=10,width=60,text=text,bg="white")
answerInput.grid(row=3,padx=(20,0),pady=20)
#answerScrollBar= Scrollbar(content,command=answerInput.yview) #command code sets the scrollbars function so it can scroll vertically
#answerInput.configure(yscrollcommand=answerScrollBar.set)
#answerScrollBar.grid(row=3,column=1,sticky="ns",pady=20)
nextButton = Button(content,borderwidth=1,22),text=("Next"+"\n"+"Question"),bg="#12a8e3",fg="black",activebackground="#12a8e3",relief="solid")
nextButton.grid(row=3,column=2,ipady=50,ipadx=70,sticky="nw",pady=20,padx=5)
header.grid(row=0,sticky='NSEW')
content.grid(row=1,sticky='NSEW')
writtenSolution.mainloop()
字符串存储在文本变量中
解决方法
解决方案是在禁用状态的情况下将文本复制并粘贴到另一个文本中。
要使窗口小部件为只读,可以将state选项从 正常到禁用:
text.config(state=NORMAL)
text.delete(1.0,END)
text.insert(END,text)
text.config(state=DISABLED)
请注意,您必须先将状态更改回NORMAL(正常) 在程序中修改窗口小部件内容。否则,请致电 插入和删除将被忽略。
为您展示可执行示例:
import tkinter as tk
root = tk.Tk()
def show_it(event):
text = write_me.get('1.0','end') #get the text
write_me.delete('1.0','end') #delet the text
write_me.index('insert')
show_me.config(state='normal')
show_me.insert('end',text)
show_me.config(state='disabled')
write_me = tk.Text(root)
write_me.pack(side='left')
write_me.bind('<Return>',show_it)
show_me = tk.Text(root,state='disabled')
show_me.pack(side='right')
root.mailoop()
还请注意,您可以执行this来简化它:
show_me = tkst.ScrolledText(root,state='disabled') #if you have python 3.7+
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。