Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การตั้งค่าสีพื้นหลังสำหรับ Tkinter ใน Python


เราสามารถปรับแต่งวิดเจ็ต tkinter โดยใช้โมดูล tkinter.ttk โมดูล Tkinter.ttk ใช้สำหรับจัดรูปแบบวิดเจ็ต tkinter เช่น การตั้งค่าสีพื้นหลัง สีพื้นหน้า การเปิดใช้งานปุ่ม เพิ่มรูปภาพในป้ายกำกับ ปรับความสูงและความกว้างของวิดเจ็ต เป็นต้น

ในการเพิ่มสีพื้นหลังในวิดเจ็ต tkinter เราสามารถระบุ พื้นหลัง คุณสมบัติในวิดเจ็ต

ตัวอย่าง

ในตัวอย่างต่อไปนี้ เราจะสร้างปุ่มที่จะเปลี่ยนพื้นหลังของป้ายกำกับข้อความ

#Import the tkinter library
from tkinter import *
from tkinter.ttk import *

#Create an instance of tkinter frame
win = Tk()

#Set the geometry
win.geometry("600x400")

#Add a class to style the tkinter widgets

style = ttk.Style()
style.configure('TEntry', foreground = 'red')

#Define a function to change the text color
def change_color():
   text.configure(background="red")

#Create a text widget
text=Label(win,text="This is a New Text",foreground="black",
background="yellow",font=('Aerial bold',20))
text.pack(pady=20)

#Create a Button widget
Button(win, text= "Click Here", command= change_color).pack(pady=10)
win.mainloop()

ผลลัพธ์

การเรียกใช้โค้ดด้านบนจะสร้างหน้าต่างที่มีป้ายกำกับข้อความที่มีสีพื้นหลังเป็น "สีเหลือง"

การตั้งค่าสีพื้นหลังสำหรับ Tkinter ใน Python

ตอนนี้ให้คลิกปุ่ม "คลิกที่นี่" มันจะเปลี่ยนสีพื้นหลังของป้ายกำกับข้อความเป็น "สีแดง"

การตั้งค่าสีพื้นหลังสำหรับ Tkinter ใน Python