0

Seems like a simple task, but I've never used tkinter before and my Python's rusty.

The print() statements are getting executed when I initially run the program but not when I press the buttons. I tried two different approaches to the buttons, but they behave the same way.

The app is going to be used for entering data into an excel table, but for now I've reduced the problem to this:


from tkinter import *
from tkinter import ttk

MAX_RECORDS=40


class MainWindow:
    def __init__(self,root):
        self.currentRow = IntVar()
        self.currentRow.set(2)

        self.label_record = Label(root,textvariable=self.currentRow)
        self.button_prev = ttk.Button(root,text="<--Previous",command=self.prev_record(self.currentRow))
        self.button_prev = ttk.Button(root,text="Next-->",command=self.next_record())
        self.label_record.grid(row=0,column=1)   
        self.button_prev.grid(row=0,column=2)     
        self.button_prev.grid(row=0,column=3)


    def prev_record(self,row):
        if row.get() > 1:
           row.set(row.get() - 1)
        print("<Row is {}".format(row.get()))

    def next_record(self):
        if self.currentRow.get() < MAX_RECORDS + 1:
            self.currentRow.set(self.currentRow.get() + 1)
        print(">Row is {}".format(self.currentRow.get()))


if __name__ == "__main__":
    root = Tk() 
    window=MainWindow(root)
    root.mainloop()
RyanN
  • 740
  • 8
  • 20
  • 1
    Read [Why is Button parameter “command” executed when declared?](https://stackoverflow.com/questions/5767228/why-is-button-parameter-command-executed-when-declared) – stovfl Feb 13 '20 at 19:18
  • I should have know better. It's been a while. – RyanN Feb 13 '20 at 19:54

1 Answers1

1

You are setting the button commands to the result of calling the next / prev record functions, instead of the functions themselves.

Change

self.button_prev = ttk.Button(root,text="Next-->",command=self.next_record())

to

self.button_prev = ttk.Button(root,text="Next-->",command=self.next_record)

and similarly for the 'Prev' button

RFairey
  • 736
  • 3
  • 9
  • Thanks, I see it now. I guess I can't pass in arguments to button commands. – RyanN Feb 13 '20 at 19:52
  • 1
    @RyanN ***" I guess I can't pass ..."***: You can, read [Python and Tkinter lambda function](https://stackoverflow.com/a/11005426/7414759) – stovfl Feb 13 '20 at 19:59