我整理了一個繼承自的簡單類,ttk.Entry以便在焦點事件上切換一些占位符文本(基于this answer)。
奇怪的是,只有'<FocusIn>' 當我包含print(self['foreground'])在我的set_placeholder()方法中時,我的占位符文本才會被清除,否則當條目被聚焦時,占位符文本不會被清除。
我已經包含了一個帶有兩個小部件的示例應用程式PlaceholderEntry來演示焦點??行為。
import tkinter as tk
from tkinter import ttk
class Root(tk.Tk):
"""Example app"""
def __init__(self):
super().__init__()
self.ph_entry_a = PlaceholderEntry(self, 'Hello')
self.ph_entry_a.pack()
self.ph_entry_b = PlaceholderEntry(self, 'there')
self.ph_entry_b.pack()
class PlaceholderEntry(ttk.Entry):
"""Entry widget with focus-toggled placeholder text"""
def __init__(
self, parent, placeholder='', color='#828790', *args, **kwargs
):
super().__init__(parent, *args, **kwargs)
self.placeholder = placeholder
self._ph_color = color
self._default_fg = self.cget('foreground') # default foreground color
# focus bindings
self.bind('<FocusOut>', self.set_placeholder)
self.bind('<FocusIn>', self.clear_placeholder)
# initialize placeholder
self.set_placeholder()
def set_placeholder(self, *args): # on focus out
if not self.get(): # if the entry has no text...
self.insert(0, self.placeholder)
self.configure(foreground=self._ph_color)
# clearing the placeholder doesn't work without this line:
print(self['foreground'])
# I've also tried this, and it works as well...
# str(self.cget('foreground'))
def clear_placeholder(self, *args):
if self.cget('foreground') == self._ph_color:
self.delete(0, tk.END)
self.configure(foreground=self._default_fg)
# it makes no difference if I have a 'print' or 'str' statement here
if __name__ == '__main__':
app = Root()
app.mainloop()
我想知道這是否與垃圾收集有關,但老實說我不確定。對于它的價值,將 分配給方法foreground中的變數set_placeholder例如fg = self['foreground']沒有區別。誰能告訴我這里發生了什么?任何資訊都非常感謝。
FWIW:我在 Windows 10 上使用 Python 3.11 64 位
uj5u.com熱心網友回復:
簡短的回答是cget回傳 a<class '_tkinter.Tcl_Obj'>而不是導致評估失敗的字串。你可以用不同的方式解決它。
self.cget('foreground').stringstr(self.cget('foreground'))
一個稍微長一點的答案,但我不知道所有細節,是所有的tcl東西都是用字串文本撰寫的,為了在 python 中有用,需要translated. 因此,您的根視窗上的此類方法,確切地說是_tkinter.tkapp存在的實體,getint等等。
tkinter 在 python 中的實作非常好,我無法想象要花費無數個小時才能讓它作業。但是有些功能并不完美。以回傳值configure為例。通常你會期望一個鍵值對的字典,但它們翻譯得不好,你也會在 tcl 中獲得關鍵字的同義詞。這是一個復雜的話題,我不會聲稱我是專家。
正如@Bryan Oakley 在評論中指出的那樣:
我認為這只是 ttk 中的一個錯誤。cget 為 ttk 小部件的顏色選項回傳此 tclObj,但它回傳帶有 tkinter 小部件的正確字串。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/522631.html
