簡體   English   中英

Python tkinter 用按鈕改變背景顏色

[英]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()

Output: 在此處輸入圖像描述

您還必須在最后添加一個.mainloop() 在某些文本編輯器中,如果不添加,程序將無法正常運行。

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM