Home > Software design >  Tkinter Button widget
Tkinter Button widget

Time:06-19

few days ago i tried to create connect between sql.connector and tkinter but I noticed there is problem with Button widget and with command option, so i tried to create a simple program with tkinter without using mysql.connector but still there's problem with it , here is my code and Button widget does not work :

from tkinter import *

win = Tk()

t1=IntVar()
t2=IntVar()

def adder():
    var1 = int(t1.get())
    var2 = int(t2.get())
    return var1   var2

win.geometry("750x750")

l1 = Label(win , text = "Number 1").grid(row = 0 , column = 0)
e1 = Entry(win , textvariable = t1).grid(row = 0 , column = 1)

l2 = Label(win , text = "Number 2").grid(row = 1 , column = 0)
e2 = Entry(win , textvariable = t2).grid(row = 1 , column = 1)

do = adder

b1 = Button(win , text = "Adder" , command = do)
b1.grid(row = 2 , column = 2)

lb = Listbox(win)
lb.grid(row = 4 , column = 4)
lb.insert(1 , do())

win.mainloop()

and the problem is Button widget doesn't even show in window , why ?

CodePudding user response:

I copied and pasted the example code and the adder button did appear. Removed the do = adder Modified the code to return the result to lb = Listbox(win) in the adder event handler.

from tkinter import *

win = Tk()

t1 = IntVar()
t2 = IntVar()


def adder(): # Button command, that is event handler.
    var1 = int(t1.get())
    var2 = int(t2.get())
    lb.insert(1, var1   var2)  # Place the update here in the event handler



win.geometry("750x750")

l1 = Label(win, text="Number 1").grid(row=0, column=0)
e1 = Entry(win, textvariable=t1).grid(row=0, column=1)

l2 = Label(win, text="Number 2").grid(row=1, column=0)
e2 = Entry(win, textvariable=t2).grid(row=1, column=1)


b1 = Button(win, text="Adder", command=adder) # make adder the event handler
b1.grid(row=2, column=2)

lb = Listbox(win)
lb.grid(row=4, column=4)
# lb.insert(1 , do()) # Update is handled in the adder event handler.
win.mainloop()

CodePudding user response:

Instead of operator We can used Python sum() Function.

 def adder():
     var1 = t1.get()
     var2 = t2.get()
     total = (var1, var2)
     lb.insert(1, sum(total))
  • Related