我的GUI设计很好。我希望能够选择显示在消息小部件中的文本。我看到的唯一建议是要么以只读模式使用Entry小部件,但这看起来与Message小部件完全不同,或者使用Text小部件又看上去完全不同。如何在消息小部件中选择文本?
如果这不可能,我如何使“文本”或“条目”小部件看起来和行为与“消息”小部件相同?
答案 0 :(得分:1)
简短的回答是不,你不能。您也许可以对事件捕获进行一些巧妙的解决方法,但是它比您预期的要多得多。
您提到的最可能的实现方法是模拟Message
或Entry
小部件上的Text
外观。一种简单的方法是使用ttk.Style
复制ttk
下的小部件的外观。但是,Message
下没有ttk
小部件,但Label
却很接近:
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
lbl = ttk.Label(root, text='foo')
lbl.winfo_class()
# 'TLabel'
# This means ttk.Label uses a 'TLabel' style
# Set a StringVar to update the message without updating the state
my_txt = tk.StringVar()
my_msg = ttk.Entry(root, text=my_txt, style='TLabel', justify='center', state='readonly')
# justify to emulate the Message look (centered).
# state = `readonly` to protect the Entry from being overwritten
my_txt.set('message here')
您的Entry
小部件现在看起来像一个Message
小部件,带有文本'message here'
的复制无需写访问权限。
编辑:如果要基于字符来调整条目的大小,并假设您使用固定长度的字体,则可以尝试以下操作:
my_msg.pack(expand=True, fill=tk.BOTH)
my_txt.set('this is a way longer message so give it a try whatever')
my_msg.configure(width=len(my_txt.get()))
如果您的字体不是固定长度,则可以估算出每个字符增加的平均/最大宽度,并将该比率乘以len()
:
my_msg.configure(width=int(len(my_txt.get())*0.85))
# where you anticipate each character might take only up to 85% of the normal character width