简体   繁体   English

Python tkinter 用按钮改变背景颜色

[英]Python tkinter change background color with a button

This is part of my code where I'm trying to create a user input field where a user can write the type of color they want their background to be, then click the button below it and make it happen.这是我的代码的一部分,我正在尝试创建一个用户输入字段,用户可以在其中编写他们希望背景颜色的类型,然后单击它下面的按钮并实现它。

I've used exactly the same code to change the color of my brush " create_oval(color, outline) and it worked yet, it doesn´t seem to affect the bg color, any suggestions?我使用完全相同的代码来更改画笔的颜色“ 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()

I fixed your code by using the .config() function.我使用.config() function 修复了您的代码。 In the background changing function, you don't attempt to change the background.在后台更改 function 时,您不要尝试更改背景。 You only change a StringVar() , which doesn't change the background anyways.您只需更改StringVar() ,无论如何都不会更改背景。

I also made your gui look better, like so:我还让你的 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()

Output: Output: 在此处输入图像描述

You also have to add a .mainloop() at the end.您还必须在最后添加一个.mainloop() In some text editors, if you don't add that, the program wont run properly.在某些文本编辑器中,如果不添加,程序将无法正常运行。

Hope this helps!希望这可以帮助!

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

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