pythontkintertkinter-canvastkinter.optionmenu

Can't change the width of the line in Canvas,through an OptionMenu value


I'm trying to create a simple paint app in tkinter. I have a function called paint and the code looks like this:

def paint( event):
    
    x1, y1, x2, y2 = ( event.x-5),( event.y-5), ( event.x+5),( event.y+5)
     
   
    Colour = "#CB5E7F"
     
    
    w.create_line( x1, y1, x2,y2, fill = Colour,width=change_width())


    
w = Canvas(root, width = 400, height = 250)
 

w.bind( "<B1-Motion>", paint)
 

l = Label( root, text = "Click and Drag to draw." )
l.place(x=150,y=400)
w.place(x=45,y=80)

I have another function called change_width, to let the user change the width of the line

def change_width():
    options= ["10","20","30"] 



    variable = StringVar(root)
    variable.set(options[0])
    #print(variable) 

    menu= OptionMenu(root, variable, *options)
    #variable.trace_add('write', lambda *args: print(variable.get()))
    menu.configure(bg="black",fg="white",font=('Arial', 14))
    menu.place(x=370,y=10)
    return variable.get()
width=Button(root,text="Change width",bg="black",fg="white",font('Arial',14),command=change_width())
width.place(x=230,y=10)

The problem is that the width doesn't change from the value that I set, and I don't understand why. Normally, it should switch to whichever value I've chosen when I click on OptionMenu.


Solution

  • Actually you don't need the Change width button and change_width() function. You just need to create the OptionMenu widget once and get the width using variable.get() inside paint():

    from tkinter import *
    
    root = Tk()
    root.geometry("600x600")
    
    def paint(event):
        x1, y1, x2, y2 = (event.x-5), (event.y-5), (event.x+5), (event.y+5)
        Colour = "#CB5E7F"
        # get the selected width directly using variable.get()
        w.create_line( x1, y1, x2, y2, fill=Colour, width=variable.get())
    
    w = Canvas(root, width=400, height=250, bg="white")
    w.bind("<B1-Motion>", paint)
    
    l = Label(root, text="Click and Drag to draw." )
    l.place(x=150, y=400)
    w.place(x=45, y=80)
    
    # create option menu for the line width
    options= ["10", "20", "30"]
    variable = StringVar(root)
    variable.set(options[0])
    
    menu= OptionMenu(root, variable, *options)
    menu.configure(bg="black", fg="white", font=('Arial', 14))
    menu.place(x=370, y=10)
    
    root.mainloop()