简体   繁体   English

使用python 3和tkinter中的colorchooser更改tkinter窗口中文本的颜色

[英]Changing color of text in a tkinter window by using colorchooser in python 3 and tkinter

Try to choose the color of the then print it, the printing bit works just need to get the color part working. 尝试选择然后打印它的颜色,打印位工作只需要让颜色部分工作。 If you need to see more of the code just ask. 如果您需要查看更多代码,请询问。

def mColour():
    color = colorchooser.askcolor()
    color_name = color[1]
    mlabel2 = Label(mGui,text=color).pack()
    messagebox.showinfo(title = "Colour",message = "This feature has not been fully added yet.")
    return
def mhello():
    mtext = ment.get()
    fg=color_name
    mlabel2 = Label(mGui,text=mtext).pack()
    return

Error: 错误:

color_name not defined

From what I can tell, you are trying to access a variable that was created within the local scope of mColour (which means it isn't in mhello 's scope). 据我所知,您正在尝试访问在mColour的本地范围内创建的变量(这意味着它不在mhello的范围内)。 You can fix this by making mColour return color_name : 您可以通过使mColour返回color_name来解决此color_name

def mColour():
    color = colorchooser.askcolor()
    color_name = color[1]
    mlabel2 = Label(mGui,text=color).pack()
    messagebox.showinfo(title = "Colour",message = "This feature has not been fully added yet.")
    #################
    return color_name
    #################

And then accessing that value in mhello like so: 然后在mhello访问该值, mhello所示:

def mhello():
    mtext = ment.get()
    ############
    fg=mColour()
    ############
    mlabel2 = Label(mGui,text=mtext).pack()

Also, I would like to address two things: 另外,我想谈两件事:

1) A bare return at the end of a function does nothing. 1)函数末尾的裸return什么都不做。

2) The pack method returns None . 2) pack方法返回None Your code should look like this: 您的代码应如下所示:

mlabel2 = Label(mGui,text=mtext)
mlabel2.pack()

Now mlabel2 points to the label like it should. 现在mlabel2指向它应该的标签。

I have found the solution with your help. 我已经在你的帮助下找到了解决方案。

#colour chooser
def mColour():
    color = colorchooser.askcolor()
    color_name = color[1]
    mlabel2 = Label(mGui,text=color).pack()
    messagebox.showinfo(title = "Colour",message = "This feature has not been fully added yet.")
    return color_name
#printing message 
def mhello():
    mtext = ment.get()
    mlabel2 = Label(mGui,text=mtext, fg = mColour()) # i put the fg and the mcolour inside here insted.
    mlabel2.pack()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM