如何在tKinter中放置条件

时间:2019-01-08 09:37:35

标签: python tkinter

我必须在程序中应用if else条件。我是python GUI的新手,无法弄清楚if语句如何放入程序中。

如果else语句如下:

if(weight>50 and glue==1):
    print("Tear in Seat")
elif(weight<50 and glue==0):
    print("No Tear in Seat")
elif(weight>70 and glue==0):
    print("Tear in Seat")
elif(weight<70 and glue==1):
    print("No tear in Seat")

这是我的GUI表单:

from tkinter import *
fields = 'Weight Applied', 'Glue 0 || 1'

def fetch(entries, weight, glue):
for entry in entries:
    field = entry[0]
    text = entry[1].get()
    print('%s: "%s"' % (field, text))
if weight > 50 and glue == 1:
    print("Tear in Seat")
elif weight < 50 and glue == 0:
    print("No Tear in Seat")
elif weight > 70 and glue == 0:
    print("Tear in Seat")
elif weight < 70 and glue == 1:
    print("No tear in Seat")

def makeform(root, fields):
   entries = []
   for field in fields:
      row = Frame(root)
      lab = Label(row, width=15, text=field, anchor='w')
      ent = Entry(row)
      row.pack(side=TOP, fill=X, padx=5, pady=5)
      lab.pack(side=LEFT)
      ent.pack(side=RIGHT, expand=YES, fill=X)
      entries.append((field, ent))
   return entries


if __name__ == '__main__':
   root = Tk()
   ents = makeform(root, fields)
   root.bind('<Return>', (lambda event, e=ents: fetch(e)))
   b1 = Button(root, text='Show', command=(lambda e=ents: fetch(e)))
   b1.pack(side=LEFT, padx=5, pady=5)
   b2 = Button(root, text='Quit', command=root.quit)
   b2.pack(side=LEFT, padx=5, pady=5)
   root.mainloop()

1 个答案:

答案 0 :(得分:1)

根据您的代码逻辑,应将if-else块放在fetch(...)函数中,如下所示:

def fetch(entries):
    weight = glue = 0
    for entry in entries:
        field = entry[0]
        text = entry[1].get()
        if 'Weight' in field:
            weight = int(text)
        elif 'Glue' in field:
            glue = int(text)
    print("weight:", weight, ", glue:", glue)
    if weight > 50 and glue == 1:
        print("Tear in Seat")
    elif weight < 50 and glue == 0:
        print("No Tear in Seat")
    elif weight > 70 and glue == 0:
        print("Tear in Seat")
    elif weight < 70 and glue == 1:
        print("No tear in Seat")
    else:
        print("Invalid weight and glue")