0

I'm trying to create a sticky-note program in Python to practice. I want to create a button such that when clicked, the background of the text box changes to yellow. My code is below:

from tkinter import *
import random


color = ['burlywood2', 'seagreen1', 'steelblue1', 'gold']
randomColor = random.choice(color)

class Sticky(Frame):
def __init__(self, master):
    Frame.__init__(self, master)
    master.minsize(width=250, height=200)
    master.configure(background=randomColor)
    self.pack(fill=BOTH, expand=YES)


    self.txtEntry = Text(background=randomColor, highlightthickness=0, relief=RAISED)
    self.txtEntry.pack(fill=BOTH, expand=YES)

    myString = input("Enter your text here: ")
    self.txtEntry.insert(END, myString)
    self.createWidgets()


def createWidgets(self):
    self.QUIT = Button(self)
    self.QUIT["text"] = "Completed"
    self.QUIT["fg"]   = "white"
    self.QUIT["background"] = "green"
    self.QUIT["command"] =  self.quit
    self.QUIT.pack(fill=BOTH, expand=YES)

    self.URGENT = Button(self)
    self.URGENT["text"] = "URGENT"
    self.URGENT["fg"] = "yellow"
    self.URGENT["background"] = "red"

    self.URGENT["command"] = self.highLight()
    self.URGENT.pack(fill=BOTH, expand=YES)

def highLight(txtEntry):
    txtEntry.configure(background='yellow')
    txtEntry.update()

I can't seem to get it to work. When the "URGENT" button is clicked, nothing happens. Thanks for any advice

1 Answers1

1

highLight is an instance method*, so its first argument should be self, not txtEntry. Even without passing it as an argument, you can still access txtEntry as an attribute of self rather than as a local name.

def highLight(self):
    self.txtEntry.configure(background='yellow')

When you do self.URGENT["command"] = self.highLight, you are telling Python "call self.highLight() right now, then take the return value of that function and assign it to the command property". But highLight returns None, so the button ends up with no command at all. Perform the assignment without the parentheses so that self.highLight is assigned to the property instead of its return value.

self.URGENT["command"] = self.highLight

(*at least, I assume it is. Your indentation is screwed up so it's not clear which of your defs are actually inside the Sticky class definition.)

Kevin
  • 74,910
  • 12
  • 133
  • 166