[英]Python tkinter change background color with a button
这是我的代码的一部分,我正在尝试创建一个用户输入字段,用户可以在其中编写他们希望背景颜色的类型,然后单击它下面的按钮并实现它。
我使用完全相同的代码来更改画笔的颜色“ create_oval(color, outline)
并且它仍然有效,它似乎不会影响背景颜色,有什么建议吗?
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()
function 修复了您的代码。 在后台更改 function 时,您不要尝试更改背景。 您只需更改StringVar()
,无论如何都不会更改背景。
我还让你的 gui 看起来更好,像这样:
import tkinter
background = "white"
okno = tkinter.Tk()
okno.title("Project")
okno.config(bg = "white")
platno = tkinter.Canvas(okno, height = 300, width = 300, bg = background, highlightthickness = 0)
platno.pack()
def background_color():
background = vstup2.get()
try:
platno.config(bg = background)
except:
pass
tkinter.Label(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="Set the color of a background", command=background_color, relief = "flat", activebackground = "white", bd = 0, bg = "white").pack()
okno.mainloop()
您还必须在最后添加一个.mainloop()
。 在某些文本编辑器中,如果不添加,程序将无法正常运行。
希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.