1

I am new to GUI programming and i'm trying to get this python program to work. What would be the correct way to call function start() so that it updates the two canvases. My code looks like this.

from Tkinter import *
class TKinter_test(Frame):
   def __init__(self,parent):
       Frame.__init__(self,parent)
       self.parent = parent
       self.initUI()

   user_reply = 0


   def accept(self):
       self.user_reply = 1
   def decline(self):
       self.user_reply = 2

   def initUI(self):
       BtnFrame = Frame (self.parent)
       BtnFrame.place(y=450, x=20)

       canvasFrame = Frame(self.parent)
       canvasFrame.place(y = 200)
       canvas_1 = Canvas(canvasFrame, width = "220", height ="200")
       canvas_2 = Canvas(canvasFrame, width = "220", height ="200")
       canvas_1.pack(side = LEFT)
       canvas_2.pack(side = RIGHT)  

       textfield_1 = canvas_1.create_text(30,50,anchor = 'w', font =("Helvetica", 17))
       textfield_2 = canvas_2.create_text(30,50,anchor = 'w', font =("Helvetica", 17))
       Accept = Button(BtnFrame, text="Friends!", width=25, command = self.accept)
       Decline = Button(BtnFrame, text="Not friends...", width=25, command = self.decline)
       Accept.pack(side = LEFT)
       Decline.pack(side = RIGHT)

   def ask_user(self,friend_1,friend_2):
       timer = 0;

       while(timer == 0):
           if(self.user_reply == 1):
               print friend_1 + " and " + friend_2 + " are friends!"
               self.user_reply = 0
               timer = 1;
           elif(user_reply == 2):
               print friend_1 + " and " + friend_2 + " are not friends..."
               self.user_reply = 0
               timer = 1

   def start(self):
       listOfPeople = ["John","Tiffany","Leo","Tomas","Stacy","Robin","Carl"]
       listOfPeople_2 = ["George","Jasmin","Rosa","Connor","Valerie","James","Bob"]
       for friend_1 in listOfPeople:
           for friend_2 in listOfPeople_2:
               ask_user(friend_1,friend_2)
       print "Finished"

def main():
    root = Tk()
    root.geometry("500x550")
    root.wm_title("Tkinter test")
    app = TKinter_test(root)
    root.mainloop()

if __name__ == '__main__':
main()

I would like to use in ask_user something that updates textfield_1 and 2. Something like textfield_1.itemconfigure(text = friend_1) and I would prefer not to use threads. Thank you.

3
  • It is unclear how you want to perform the update. Apr 25, 2016 at 8:41
  • Well, every time the function start() calls for the function ask_user() I want it to update the view with the two names of the friends list and wait for the user to give an answer of whether or not they are friends with buttons Accept/Decline @BillalBEGUERADJ
    – Nate
    Apr 25, 2016 at 10:05
  • Sorry for the late response, but hopefully my code will be helpful.
    – PM 2Ring
    Apr 25, 2016 at 12:30

1 Answer 1

0

It takes a different mindset to do event-driven programming, and it can be a bit frustrating and bewildering at first. I suggest that you take a look at code in the high-scoring Tkinter answers on Stack Overflow, and experiment with it, making small changes and see what happens. As you become more familiar with it it will begin to make sense. :)

I don't know why you want all those Frame and Canvas objects, so I've simplified the GUI to use a single Frame, "borrowing" Bryan Oakley's template from this answer. Rather than using Canvas text items to display the friend names I just use simple Label widgets.

Instead of hard-coding the friends lists into the GUI class I pass them in a tuple to the GUI constructor as a keyword argument, friendlists. We have to remove that argument from kwargs before passing kwargs on to the Frame.__init__ method, since that method treats keyword args it doesn't recognize as errors.

I create a generator expression self.pairs which uses a double for loop to yield the pairs of friend names. Calling next(self.pairs) gives us the next pair of friend names.

When a Button is pressed the test_friends method is called with a reply arg of True or False, depending on whether the "Friends!" or "Not friends." button is pressed.

test_friends prints the information about the current pair of friends and then calls the set_friends method to set the names of the next pair of friends in the Labels. If there are no pairs left, then the program exits.

import Tkinter as tk

class MainApplication(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        # Extract the friend lists from the keyword args 
        friends1, friends2 = kwargs['friendlists']
        del kwargs['friendlists']

        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent

        # A generator that yields all pairs of people from the friends lists
        self.pairs = ((u, v) for u in friends1 for v in friends2)

        # A pair of labels to display the names
        self.friend1 = tk.StringVar()
        tk.Label(self, textvariable=self.friend1).grid(row=0, column=0)

        self.friend2 = tk.StringVar()
        tk.Label(self, textvariable=self.friend2).grid(row=0, column=1)

        # Set the first pair of names
        self.set_friends()

        cmd = lambda: self.test_friends(True)
        b = tk.Button(self, text="Friends!", width=25, command=cmd)
        b.grid(row=1, column=0)

        cmd = lambda: self.test_friends(False)
        b = tk.Button(self, text="Not friends.", width=25, command=cmd)
        b.grid(row=1, column=1)

    def set_friends(self):
        # Set the next pair of names
        f1, f2 = next(self.pairs)
        self.friend1.set(f1)
        self.friend2.set(f2)

    def test_friends(self, reply):
        f1, f2 =  self.friend1.get(), self.friend2.get()
        reply = (' not ', ' ')[reply]
        print '%s and %s are%sfriends' % (f1, f2, reply)
        try:
            self.set_friends()
        except StopIteration:
            # No more pairs
            print 'Finished!'
            self.parent.destroy()


def main():
    people_1 = [
        "John", 
        "Tiffany", 
        "Leo", 
        "Tomas", 
        #"Stacy", 
        #"Robin", 
        #"Carl",
    ]

    people_2 = [
        "George", 
        "Jasmin", 
        "Rosa", 
        #"Connor", 
        #"Valerie", 
        #"James", 
        #"Bob",
    ]

    root = tk.Tk()
    root.wm_title("Friend Info")
    app = MainApplication(root, friendlists=(people_1, people_2))
    app.pack()
    root.mainloop()

if __name__ == "__main__":
    main()
1
  • Thank you! I'm positive I can make my program work with this.
    – Nate
    Apr 29, 2016 at 4:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.