Python 使Tkinter在不单击或按下按钮的情况下运行命令

Python 使Tkinter在不单击或按下按钮的情况下运行命令,python,tkinter,Python,Tkinter,我正在制作一个简单的tkinter弹出窗口,您可以在其中键入消息。 在文本框本身中,我插入了灰色的文本“在此处键入您的消息”,单击时,插入的文本将被删除,以便用户可以键入自己的消息。此外,用户键入的文本颜色设置为黑色 然而,当我进行测试时,我意识到只有当他们用鼠标点击文本框时才会发生这种情况。我的问题是,tkinter有没有办法在条件改变时自动运行命令?例如,如果文本框为空,则字体颜色应设置为黑色。 我试着将if语句放入tk.mainloop,但遗憾的是,这没有起作用 有什么想法吗 这是我(希望

我正在制作一个简单的
tkinter
弹出窗口,您可以在其中键入消息。 在文本框本身中,我插入了灰色的文本“在此处键入您的消息”,单击时,插入的文本将被删除,以便用户可以键入自己的消息。此外,用户键入的文本颜色设置为黑色

然而,当我进行测试时,我意识到只有当他们用鼠标点击文本框时才会发生这种情况。我的问题是,
tkinter
有没有办法在条件改变时自动运行命令?例如,如果文本框为空,则字体颜色应设置为黑色。
我试着将if语句放入
tk.mainloop
,但遗憾的是,这没有起作用

有什么想法吗

这是我(希望如此)简化的代码版本:

from tkinter import *

def changecolor(event):
    if textbox.get("1.0", "end-1c") == "Type your message here":
        textbox.delete("1.0", "end")
        textbox.config(fg='black')

root = Tk()

canvas = Canvas(root, height=400, width=600)
canvas.pack()

textbox = Text(canvas, font=40, fg="grey")
textbox.insert(1.0, "Type your message here")
textbox.bind("<Button-1>", changecolor)
textbox.pack()

root.mainloop()
从tkinter导入*
def CHANGECLOR(事件):
如果textbox.get(“1.0”,“end-1c”)=“在此处键入您的消息”:
文本框。删除(“1.0”,“结束”)
textbox.config(fg='black')
root=Tk()
画布=画布(根,高度=400,宽度=600)
canvas.pack()
textbox=Text(画布,font=40,fg=“灰色”)
textbox.insert(1.0,“在此处键入您的消息”)
textbox.bind(“,changecolor)
textbox.pack()
root.mainloop()

~终于找到了如何在这里格式化代码。

看看我创建的这个类,它的功能与您的代码类似,一定要试一试

from tkinter import *

class PlaceholderText(Text):
    def __init__(self,master,placeholder,placeholdercolor='black',fg='grey',**kwargs):
        Text.__init__(self,master,**kwargs) #init the text widget
        self.placeholder = placeholder 
        self.fgcolor = fg
        self.placeholdercolor = placeholdercolor
        self.has_placeholder = False #make flag

        self.add() #run the function to add placeholder
        self.bind('<FocusIn>',self.clear) #binding to focusin and not button-1
        self.bind('<FocusOut>',self.add) #function wil get triggered when widget loses focus

    def clear(self,event=None):
        if self.get('1.0','end-1c') == self.placeholder and self.has_placeholder: #condition to clear a placeholder
            self.delete('1.0','end-1c') #delete the placeholder
            self.config(fg=self.fgcolor) #change the color
            self.has_placeholder = False #set flag to flase

    def add(self,event=None):
        if self.get('1.0','end-1c') == '' and not self.has_placeholder: #condition to add placeholder
            self.insert('1.0',self.placeholder) #add placeholder
            self.has_placeholder = True #set flag to true
            self.config(fg=self.placeholdercolor) #change text color to what you specify?

    def ret(self,index1,index2):
        if self.get('1.0','end-1c') == self.placeholder and self.has_placeholder: #gives none if there is nothing in the widget
            return 'None'
        else:
            return self.get(index1,index2) #else gives the text
root = Tk()

pl = PlaceholderText(root,placeholder='Type something here...')
pl.pack()

e = Entry(root) #dummy widget to switch focus and check
e.pack(padx=10,pady=10)

root.mainloop()
从tkinter导入*
类占位符文本(文本):
定义初始值(自、主、占位符、占位符颜色='黑色'、前景='灰色'、**kwargs):
文本。初始化(self,master,**kwargs)#初始化文本小部件
self.placeholder=占位符
self.fgcolor=fg
self.placeholder颜色=placeholder颜色
self.has_placeholder=False#生成标志
self.add()#运行函数以添加占位符
自我绑定(“”,自我清除)#绑定到焦点而不是按钮-1
self.bind(“”,self.add)#函数将在小部件失去焦点时触发
def清除(自身,事件=无):
如果self.get('1.0','end-1c')==self.placeholder和self.has_placeholder:#清除占位符的条件
self.delete('1.0','end-1c')#删除占位符
self.config(fg=self.fgcolor)#更改颜色
self.has_placeholder=False#将标志设置为flase
def添加(自身,事件=无):
如果self.get('1.0','end-1c')=''而不是self.has_占位符:#添加占位符的条件
self.insert('1.0',self.placeholder)#添加占位符
self.has_placeholder=True#将标志设置为True
self.config(fg=self.placeholdercolor)#将文本颜色更改为您指定的颜色?
def ret(自、索引1、索引2):
如果self.get('1.0','end-1c')==self.placeholder和self.has_placeholder:#如果小部件中没有任何内容,则给出none
返回“无”
其他:
返回self.get(index1,index2)#else给出文本
root=Tk()
pl=占位符文本(根,占位符=“在此处键入某物…”)
pl.pack()
e=条目(根)#切换焦点和检查的虚拟小部件
e、 包装(padx=10,pady=10)
root.mainloop()
我已经通过评论向你解释了。但是请记住,它还不是最好的类,您必须添加更多的方法来提高效率

如果您想知道如何在没有课程的情况下做到这一点,那么:

from tkinter import *

has_placeholder = False #make flag
placeholder = 'Type Something Here...' #the text to be inserted

def clear(event=None):
    global has_placeholder
    if a.get('1.0','end-1c') == placeholder and has_placeholder: #condition to clear a placeholder
        a.delete('1.0','end-1c') #delete the placeholder
        a.config(fg='grey') #change the color
        has_placeholder = False #set flag to flase

def add(event=None):
    global has_placeholder
    if a.get('1.0','end-1c') == '' and not has_placeholder: #condition to add placeholder
        a.insert('1.0',placeholder) #add placeholder
        has_placeholder = True #set flag to true
        a.config(fg='black') #change text color to normal

root = Tk()

a = Text(root)
a.pack()

add() #add the placeholder initially
a.bind('<FocusIn>',clear) #binding to focus and not button-1
a.bind('<FocusOut>',add)

e = Entry(root) #dummy widget to show focus loss
e.pack()
root.mainloop()
从tkinter导入*
has_placeholder=False#make标志
占位符='在此处键入某物…'#要插入的文本
def清除(事件=无):
全局占位符
如果a.get('1.0','end-1c')==占位符并具有_占位符:#清除占位符的条件
a、 删除('1.0','end-1c')#删除占位符
a、 配置(fg='grey')#更改颜色
已将_placeholder=False#将标志设置为flase
def添加(事件=无):
全局占位符
如果a.get('1.0','end-1c')==''且没有占位符:#添加占位符的条件
a、 插入('1.0',占位符)#添加占位符
已将_placeholder=True#将标志设置为True
a、 配置(fg='black')#将文本颜色更改为正常
root=Tk()
a=文本(根)
a、 包()
add()#最初添加占位符
a、 绑定(“”,清除)#绑定到焦点而不是按钮-1
a、 绑定(“”,添加)
e=条目(根)#显示焦点丢失的虚拟小部件
e、 包()
root.mainloop()
如果后一种方法更简单,为什么不使用类呢?这是不可重用的,比如说你想再添加一个文本小部件,它不能有这样的属性,而使用自定义类和自定义类时,你可以有尽可能多的文本小部件和你喜欢的相同属性


如果有任何疑问,请告诉我。

您只需在文本小部件中添加一个
绑定,并使用
changecolor
功能确定
文本框的状态

#Give a hoot. Don't pollute. :D
import tkinter as tk

txtmsg = "Type your message here"

def changecolor(event):
    text = textbox.get("1.0", "end-1c")
    
    #customize accordingly
    if text:
        if text == txtmsg:
            print("text is txtmsg")
        else:
            print("text is user text")
    else:
        print("text is empty")

    #FYI:
    #whether this was a button press or key press DOES NOT have string equality
    #if you need to create button vs key conditions
    #use tk.EventType.ButtonPress and tk.EventType.KeyPress
    #or learn the .value and compare that
    print(event.type, type(event.type), event.type.value)


root = tk.Tk()

textbox = tk.Text(root, font=40, fg="grey")
textbox.insert(1.0, txtmsg)
textbox.pack()

#add events
for ev in ['<Key>', '<1>']:
    textbox.bind(ev, changecolor)

root.mainloop() 
#发出嘘声。不要污染环境D
将tkinter作为tk导入
txtmsg=“在此处键入您的消息”
def CHANGECLOR(事件):
text=textbox.get(“1.0”,“end-1c”)
#相应定制
如果文本:
如果text==txtmsg:
打印(“文本为txtmsg”)
其他:
打印(“文本即用户文本”)
其他:
打印(“文本为空”)
#供参考:
#无论这是按钮按下还是按键按下,字符串都不相等
#如果需要创建按钮与关键条件
#使用tk.EventType.ButtonPress和tk.EventType.KeyPress
#或者学习价值观,并进行比较
打印(event.type、type(event.type)、event.type.value)
root=tk.tk()
textbox=tk.Text(根,font=40,fg=“灰色”)
textbox.insert(1.0,txtmsg)
textbox.pack()
#添加事件
对于['',''中的ev:
textbox.bind(ev,changecolor)
root.mainloop()

您要查找的内容称为占位符。这个网站上有很多关于占位符的问题。看看我做了什么,或者你可以在这个网站上搜索更多的Q,甚至可以查看我在这个网站上问的Q。非常感谢你的帮助!我还不了解类,所以另一个解决方案是