我制作了一个继承自ttk.Entry. 问题是,它只适用于实例化一次,如果我为同一个条目创建两个实例,它将开始显示一些奇怪的效果。
类及其用法:
import tkinter as tk
from tkinter import ttk
class PlaceholderEntry(ttk.Entry):
'''
Custom modern Placeholder Entry box, takes positional argument master and placeholder\n
Use acquire() for getting output from entry widget\n
Use shove() for inserting into entry widget\n
Use remove() for deleting from entry widget\n
Use length() for getting the length of text in the widget\n
BUG 1: Possible bugs with binding to this class\n
BUG 2: Anomalous behaviour with config or configure method
'''
def __init__(self, master, placeholder, **kwargs):
# style for ttk widget
self.s = ttk.Style()
self.s.configure('my.TEntry')
# init entry box
ttk.Entry.__init__(self, master, style='my.TEntry', **kwargs)
self.text = placeholder
self.__has_placeholder = False # placeholder flag
# add placeholder if box empty
self._add()
# bindings of the widget
self.bind('<FocusIn>', self._clear)
self.bind('<FocusOut>', self._add)
self.bind_all('<Key>', self._normal)
self.bind_all('<Button-1>', self._cursor)
def _clear(self, *args): # method to remove the placeholder
if self.get() == self.text and self.__has_placeholder: # remove placeholder when focus gain
self.delete(0, tk.END)
self.s.configure('my.TEntry', foreground='black',
font=(0, 0, 'normal'))
self.__has_placeholder = False # set flag to false
单击其中一个条目并将焦点更改到下一个条目时,您可以注意到两个实例在某种程度上有关联的“行为”?尽管单个实例工作得很好。这是我的第一个 OOP 项目,所以我不确定出了什么问题。
先谢谢了
BIG阳
相关分类