Python - gui - tkinter 获取入口值

Python - gui - tkinter Getting entry values

您好,我正在制作一个 python tkinter gui,它使用沃尔玛 api 并允许您根据 ID 号搜索任何项目。我无法开始工作的是提交按钮,它不会做任何事情。非常感谢任何帮助。

import tkinter as tk
from tkinter import *
import tkinter.messagebox


def displayText():

    global queryurl
    global ItemIdEntry
    global GetItemId


    if ItemIdEntry.get().strip() == "":
    tkinter.messagebox.showerror("Item Checker", "Enter an item id number! ")
    else:
        try:
            import urllib.request as urllib2
        except ImportError:
            import urllib2

        import json

        GetItemId = ItemIdEntry.get().strip()



        queryurl = ('http://walmartlabs.api.mashery.com/v1/items/'+GetItemId+'?format=json&apiKey=phutmkv9t262zj7dmbk8hkec')

        f = urllib2.urlopen(queryurl)
        json_string = f.read().decode('utf-8' )
        parsed_json = json.loads(json_string)

        itemName = parsed_json['name']
        currentprice = parsed_json['salePrice']
        upc = parsed_json['upc']
        producturl = parsed_json['productUrl']
        description = parsed_json['shortDescription']
        online = parsed_json['availableOnline']
        modelnumber = parsed_json['modelNumber']

        print ('Name:', itemName)
        print ('Current Price:', '$', currentprice)
        print ('Upc Number:', upc)
        print ('Model Number:', modelnumber)
        print ('Purchaseable Online:', online)
        print ('Description:', description)
        print ('Product Url:', producturl)

        f.close()


if __name__ == "__main__":

    root = tk.Tk()
    root.geometry("%dx%d+%d+%d" % (250, 100, 250, 100))
    var = tk.StringVar(root)
    root.title("Item Checker")   

    itemName = Label(root, text="Please enter an id number")
    itemName.pack(side = TOP)

    ItemIdEntry = Entry(root, bd =5)
    ItemIdEntry.pack(side = TOP)

    submitbutton = tkinter.Button(root, text ="Submit", command = displayText)#Submit button
    submitbutton.pack()




root.mainloop()

只是让它正式化。问题在于缩进。具体而不是这个:

if ItemIdEntry.get().strip() == "":
tkinter.messagebox.showerror("Item Checker", "Enter an item id number! ")

应该有:

if ItemIdEntry.get().strip() == "":
    tkinter.messagebox.showerror("Item Checker", "Enter an item id number! ")

你会期待什么?您在该函数中打印值。你不要展示它们。例如,而不是这个;

print ('Name:', itemName)

你应该用这个;

lbl = Label(text="{}".format(itemName), fg="red",font="Times 35 bold")
lbl.pack()

这样无论何时单击按钮,您的函数都会显示它们。