【问题标题】:Python tkinter change background color with a buttonPython tkinter 使用按钮更改背景颜色
【发布时间】:2020-10-09 23:10:21
【问题描述】:

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

我使用完全相同的代码来更改我的画笔颜色“ 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()

【问题讨论】:

  • 你想改变哪个小部件的颜色?
  • 你在用StringVar换颜色吗?
  • 你似乎并没有试图改变任何地方的背景。
  • 此:vstup2.set(background) 应改为:platno.configure(bg=background)。同时修复你的缩进错误。

标签: python python-3.x button tkinter background-color


【解决方案1】:

我使用.config() 函数修复了您的代码。在背景更改功能中,您不会尝试更改背景。您只需更改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()。在某些文本编辑器中,如果不添加,程序将无法正常运行。

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2016-09-10
    • 2016-09-11
    • 2015-06-04
    • 1970-01-01
    • 2023-04-10
    • 2021-06-22
    • 2015-04-03
    相关资源
    最近更新 更多