Tkinter循环功能

时间:2016-04-25 08:29:38

标签: python loops user-interface tkinter

我是GUI编程的新手,我试图让这个python程序工作。调用函数start()以便更新两个画布的正确方法是什么。我的代码看起来像这样。

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()

我想在ask_user中使用更新textfield_1和2.像textfield_1.itemconfigure(text = friend_1)这样的东西,我宁愿不使用线程。 谢谢。

1 个答案:

答案 0 :(得分:0)

进行事件驱动编程需要不同的思维方式,一开始可能有点令人沮丧和困惑。我建议您在Stack Overflow上查看高分Tkinter答案中的代码,然后进行实验,进行小的更改,看看会发生什么。随着你越来越熟悉它,开始变得有意义。 :)

我不知道为什么你想要所有FrameCanvas个对象,所以我简化了GUI以使用单个Frame,“借用”Bryan Oakley的模板this answer。我只使用简单的Canvas小部件,而不是使用Label文本项来显示朋友名称。

我没有将好友列表硬编码到GUI类中,而是将它们作为关键字参数friendlists传递给GUI构造函数。在将kwargs传递给kwargs方法之前,我们必须从Frame.__init__中删除该参数,因为该方法会处理它不会识别为错误的关键字args。

我创建了一个生成器表达式self.pairs,它使用双for循环来生成朋友名称对。致电next(self.pairs)会给我们下一对朋友的名字。

当按下Button时,调用test_friends方法的reply arg为TrueFalse,具体取决于“朋友”!或“不是朋友”。按下按钮。

test_friends打印有关当前朋友对的信息,然后调用set_friends方法设置Labels中下一对朋友的姓名。如果没有对,则程序退出。

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()