我写了这段代码:
from tkinter import *
count = 0
def click_button():
global count
count += 1
print("You have clicked the button "+str(count)+" Times")
def submit():
Username = Enter_Box.get()
print("You have set your username to: "+Username)
delete()
Enter_Box.config(state=DISABLED)
def delete():
Enter_Box.delete(0,END)
def backspace():
Enter_Box.delete(len(Enter_Box.get())-1,END)
def display():
if (Check_Button_Status.get()==1):
print("You agree")
else:
print("You don't agree")
def click(event):
Enter_Box.delete(0,END)
Window = Tk()
Photo = PhotoImage(file="Pig2.png")
Like_Button = PhotoImage(file="Like-Button2.png")
Window.geometry("900x600")
Window.title("The Ultimate GUI Program")
Window.iconbitmap("AngryBird9.ico")
button = Button(Window,
text="Click me",
command=click_button,
font=("Comic Sans,",10,"bold"),
fg="Red",
bg="black",
activeforeground="Red",
activebackground="black",
image=Like_Button,
compound="bottom")
button.place(x=50,y=50)
Window.config(background="white")
#Adding an image and text onto the Window:
Label = Label(Window,
text="You are using the best program ever!",
font=("Arial",10,"bold"),
fg="red",
bg="white",relief=RAISED,bd=10,
padx=10,
pady=10,image=Photo,
compound="bottom")
Label.place(x=170,y=170)
Enter_Box = Entry(Window,font=("Arial"),fg="Black",bg="Gray")
Enter_Box.place(x=460,y=220)
Submit_button = Button(Window,
text="Submit",
command=submit)
Submit_button.place(x=700,y=220)
Delete_button = Button(Window,
text="Delete",
command=delete)
Delete_button.place(x=750,y=220)
BackSpace_button = Button(Window,
text="Backspace",
command=backspace)
BackSpace_button.place(x=795,y=220)
Check_Button_Status = IntVar()
Checkbox = Checkbutton(Window,
text="I agree to the TOS",
variable=Check_Button_Status,
onvalue=1,
offvalue=0,
command=display)
Checkbox.place(y=100,x=200)
Enter_Box.insert(0,"Enter username")
Enter_Box.bind("<Button-1>",click)
Window.mainloop()
谁创建了这个 GUI 程序:
但是,当我按下输入“用户名”的输入框时,它会删除“输入用户名”的占位符,就像大多数网站一样,但是在提交用户名(例如“赞”按钮或 TOS 协议)之前单击其他项目时,此占位符没有像我希望的那样回来。
提交前按不同项目时如何实现此占位符的替换?我猜测我需要以某种方式检测在单击不同的项目后何时再次单击此输入框,但我不知道该怎么做。
我已经在 YouTube 上搜索过这个内容,但是我在某种程度上能理解的所有视频都在没有替换的情况下进行了此操作,我发现其中一个视频具有它,因此当您的鼠标离开该框时,它会替换占位符。
最直接的选项是创建一个继承自
Entry
(tk.Entry
或 ttk.Entry
)的自定义小部件类。这是一个带有 PlaceholderEntry
小部件的基本示例应用程序 - 您可以在任何需要带有占位符值的 Entry
的地方使用它。
注意:这里的
Button
只是为了给予其他焦点,这样当您单击远离它时,如果条目为空,您可以看到占位符文本会重新填充。
import tkinter as tk
from tkinter import ttk
class App(tk.Tk):
def __init__(self) -> None:
super().__init__()
self.geometry('400x400')
self.title('Placeholder Entry Example')
self.entry = PlaceholderEntry(self, 'placeholder text')
self.entry.pack()
self.btn = ttk.Button(self, text='Does Nothing')
self.btn.pack()
class PlaceholderEntry(ttk.Entry):
"""Entry widget with focus-toggled placeholder text"""
def __init__(
self, parent, placeholder='', color='#828790', *args, **kwargs
) -> None:
super().__init__(parent, *args, **kwargs)
self.placeholder = placeholder
self._ph_color = color
self._default_fg = self._get_fg_string() # default fg color
# focus bindings
self.bind('<FocusIn>', self.clear_placeholder)
self.bind('<FocusOut>', self.set_placeholder)
# initialize the placeholder
self.set_placeholder()
def clear_placeholder(self, *args) -> None: # on focus in
"""Clear the placeholder text"""
if self._get_fg_string() == self._ph_color:
self.delete(0, tk.END)
self.configure(foreground=self._default_fg)
def set_placeholder(self, *args) -> None: # on focus out
"""Restore the placeholder text"""
if not self.get(): # if the entry has no text...
self.insert(0, self.placeholder)
self.configure(foreground=self._ph_color)
def _get_fg_string(self) -> str:
# Get string representation of the foreground color, otherwise 'cget'
# returns a '_tkinter.Tcl_Obj' and focus won't clear the placeholder
# This may be a bug in ttk
# https://github.com/python/cpython/issues/98815
return str(self.cget('foreground'))
def ph_get(self) -> str:
"""
Return the text. Wraps the builtin `get()` method to return an empty
string if the placeholder is being shown, because using the regular
`get()` method would otherwise return the placeholder text
"""
return '' if (content := self.get()) == self.placeholder else content
if __name__ == '__main__':
app = App()
app.mainloop()
我还添加了一个名为
ph_get()
的辅助方法,您可以使用它来代替标准 Entry.get()
,否则它会返回占位符文本,其中 ph_get
如果显示占位符,则返回一个空字符串。