Python tkinter使用按钮更改背景色

Python tkinter使用按钮更改背景色,python,python-3.x,button,tkinter,background-color,Python,Python 3.x,Button,Tkinter,Background Color,这是我的代码的一部分,我试图创建一个用户输入字段,用户可以在该字段中写入他们希望其背景的颜色类型,然后单击它下面的按钮并实现它 我使用了完全相同的代码来更改画笔的颜色” create_oval(颜色、轮廓)效果还不错,似乎不会影响背景颜色,有什么建议吗 import tkinter background = "white" okno = tkinter.Tk() okno.title("Project") platno = tkinter.Canvas(okno, height = 300, w

这是我的代码的一部分,我试图创建一个用户输入字段,用户可以在该字段中写入他们希望其背景的颜色类型,然后单击它下面的按钮并实现它

我使用了完全相同的代码来更改画笔的颜色”
create_oval(颜色、轮廓)
效果还不错,似乎不会影响背景颜色,有什么建议吗

import tkinter
background = "white"
okno = tkinter.Tk()
okno.title("Project")
platno = tkinter.Canvas(okno, height = 300, width = 300, bg = background)
platno.pack()

 def background_color():
    background = vstup2.get()
    vstup2.set(background)

tkinter.Label(okno,text = "Background color :", bg = "white", width = 30).pack()
vstup2 = tkinter.StringVar()
tkinter.Entry(okno,textvariable = vstup2, ).pack()
tkinter.Button(okno,width=30, text="Set the color of a background", command=background_color).pack()

我使用
.config()
函数修复了您的代码。在后台更改函数中,您不尝试更改背景。您只更改
StringVar()
,这不会更改背景

我还使您的gui看起来更好,如下所示:

导入tkinter
背景=“白色”
okno=tkinter.Tk()
okno.名称(“项目”)
okno.config(bg=“白色”)
platno=tkinter.Canvas(okno,高度=300,宽度=300,背景=background,highlightthickness=0)
platno.pack()
def background_color():
background=vstup2.get()
尝试:
platno.config(bg=background)
除:
通过
标签(okno,text=“Background color:,bg=“white”,width=30).pack()
vstup2=tkinter.StringVar()
tkinter.Entry(okno,textvariable=vstup2,bg=“white”).pack()
tkinter.Button(okno,width=30,text=“设置背景颜色”,command=background\u color,relief=“flat”,activebackground=“white”,bd=0,bg=“white”).pack()
okno.mainloop()
输出:

您还必须在末尾添加一个
.mainloop()
。在某些文本编辑器中,如果不添加,程序将无法正常运行


希望这有帮助!

您想更改哪个小部件的颜色?您正在使用
StringVar
更改颜色吗?您似乎没有尝试在任何地方更改背景。此:
vstup2.set(background)
应为:
platno.configure(bg=background)
。还应修复缩进错误。