Python tkinter binding a function to a button

前端 未结 1 619
忘了有多久
忘了有多久 2021-01-16 06:32
from tkinter import *

root = Tk()
root.title(\"Tip & Bill Calculator\")

totaltxt = Label(root, text=\"Total\", font=(\"Helvitca\", 16))
tiptxt = Label(root, te         


        
相关标签:
1条回答
  • 2021-01-16 06:40
    1. Commands bound to a button do not get an argument, as the nature of the event is already known. Delete 'event'.

    2. You also bind the answer function to an event. The result is that answer is called both without and with an event argument. Get rid of the bind call.

    3. Follow hint given by Bryan. Stop passing a digit string to .configure as a positional parameter. tk will try to interpret is as dictionary. Instead, add the number string to the rest of the label string.

    4. Like rows, columns start from 0.

    5. The frame is not needed.

    The following revision works.

    from tkinter import *
    
    root = Tk()
    root.title("Tip & Bill Calculator")
    
    totaltxt = Label(root, text="Total", font=("Helvitca", 16))
    tiptxt = Label(root, text="Tip (%)", font=("Helvitca", 16))
    peopletxt = Label(root, text="people", font=("Helvitca", 16))
    
    totaltxt.grid(row=0, column=0, sticky=E)
    tiptxt.grid(row=1, column=0, sticky=E)
    peopletxt.grid(row=2, column=0, sticky=E)
    
    totalentry = Entry(root)
    tipentry = Entry(root)
    peopleentry = Entry(root)
    
    totalentry.grid(row=0, column=1)
    tipentry.grid(row=1, column=1)
    peopleentry.grid(row=2, column=1)
    
    ans = Label(root, text = "ANS")
    ans.grid(row=4, column=0, columnspan=2, sticky=W)
    
    def answer():
        total = totalentry.get()
        tip = tipentry.get()
        people = peopleentry.get()
        if not (total and tip):
            ans['text'] = 'Enter total and tip as non-0 numbers'
        else:
            total = float(total)
            tip = float(tip) / 100
            people = int(people) if people else 1
            ans['text'] = str(round(total * tip / people, 2)) + " per person"
    
    calc = Button(root, text ="Calculate", fg = "black", command = answer)
    calc.grid(row=3, column=1)
    
    root.mainloop()
    
    0 讨论(0)
提交回复
热议问题