简体   繁体   English

从输入字段tkinter存储用户输入

[英]Store user entry from entry field, tkinter

So, I've seen other questions on a similar topic to this, I've struggled to make sense of them so I'm asking this one. 因此,我已经看到了与此主题类似的其他问题,我一直难以理解它们,所以我要问这个问题。

I have this program, the majority of the code is below, It's a basic GUI. 我有这个程序,大部分代码在下面,这是一个基本的GUI。

I'm having problems with the entry fields that take the users first name and surname, the block of code associated with this is here: 我在使用用户名和姓氏的输入字段中遇到问题,与此相关的代码块在此处:

tk.Label(self, text='First Name: ').pack(side=TOP)
EntryFieldFN = Entry(self)
EntryFieldFN.pack(pady=2, padx=2)

tk.Label(self, text='Surname: ').pack()
EntryFieldSN = Entry(self)
EntryFieldSN.pack(pady=2, padx=2)

FirstName = EntryFieldFN.get()
Surname = EntryFieldSN.get()  

I've been unable to work out how to store the user input from these fields into variables that I can then use later. 我一直无法弄清楚如何将这些字段中的用户输入存储到变量中,以便以后使用。 I wish to use the first name and surname of the user in the FinalWindow() function, which I want to act as a receipt of purchase for the order. 我希望在FinalWindow()函数中使用用户的名字和姓氏,我想将其用作订单的购买收据。

def FinalWindow():
    win = Toplevel()
    LabelRW = Label(win, text='Receipt of Purchase')
    ExitProg = Button(win, text='Exit', command=sys.exit)
    LabelRW.pack()
    ExitProg.pack()
    win.title('Virtual Receipt')

class Till(tk.Frame):
    def __init__(self, master=None, **kw):
        tk.Frame.__init__(self, master=master, **kw)
        self.price_string = tk.StringVar()
        tk.Label(self, text='GUI Program - Till System').pack(side=TOP)
        tk.Label(self, text='First Name: ').pack(side=TOP)

        EntryFieldFN = Entry(self)
        EntryFieldFN.pack(pady=2, padx=2)

        tk.Label(self, text='Surname: ').pack()
        EntryFieldSN = Entry(self)
        EntryFieldSN.pack(pady=2, padx=2)

        FirstName = EntryFieldFN.get()
        Surname = EntryFieldSN.get()

        tk.Label(self, textvariable=self.price_string).pack(side=BOTTOM)
        tk.Label(self, text="Total Price: ").pack(side=BOTTOM)
        self.items = []

    # For each stock item, create an IntVar, a checkbox and keep record of the price/name

        for idx, item in enumerate(stock_items):
            new_item = {}
            new_item['var'] = tk.IntVar()
            new_item['check'] = tk.Checkbutton(self, text=item['name'], variable=new_item['var'], command=self.recalculate)
            new_item['check'].pack()
            new_item['name'] = item['name']
            new_item['price'] = item['price']
            self.items.append(new_item)

        ExitButton = Button(root, text='Exit', command=sys.exit)
        OrderButton = Button(root, text='Order', command=FinalWindow)
        ExitButton.pack(side=BOTTOM, padx=2, pady=2)
        OrderButton.pack(side=BOTTOM, padx=2, pady=2)
        ExitButton.config(height=1, width=8)
        OrderButton.config(height=1, width=8)

# Recalculate is called when ever a checkbox is checked/unchecked

    def recalculate(self):
        total_price = 0

    # Go through each item and if it is selected add its price to the total

        for item in self.items:
            if item['var'].get():
                total_price += item['price']

    # Display out total price

        self.price_string.set('£ {:.2f}'.format(total_price))

if __name__ == '__main__':
    root = tk.Tk()
    Till(root).pack()
    root.mainloop()

I've tried a couple of things so far, none of which have worked, I don't know if it would be a good idea to use global variables for the inputs. 到目前为止,我已经尝试了几件事,但都没有奏效,我不知道将全局变量用作输入是否是一个好主意。

There are at least two ways to solve this problem. 至少有两种方法可以解决此问题。 Both of them start by having your button call a method which is part of the class: 两者都始于让您的按钮调用属于该类的方法:

OrderButton = Button(root, text='Order', command=self.do_order)

You also need to make sure that you keep a reference to the entry widgets, so instead of EntryFieldFN and EntryFieldSN you should use self.EntryFieldFN and self.EntryFieldSN . 您还需要确保你到录入组件的参考,所以不是EntryFieldFNEntryFieldSN你应该使用self.EntryFieldFNself.EntryFieldSN This is so that you can get access to the widgets from anywhere in the class. 这样,您就可以从类中的任何位置访问窗口小部件。

def __init__(self, master=None, **kw):
    ...
    self.EntryFieldFN = Entry(self)
    self.EntryFieldSN = Entry(self)
    ...

Note: this concept applies to all other input widgets (eg: the Checkbuttons). 注意:此概念适用于所有其他输入小部件(例如:Checkbuttons)。 I'm limiting the answer to these two widgets to make the code examples smaller and easier to manage. 我将答案限制在这两个小部件上,以使代码示例更小且更易于管理。

With that out of the way, you can do one of two things: your function can get the values and pass it to FinalWindow , or it can pass itself to FinalWindow and let FinalWindow get the values it needs. 这样一来,您可以执行以下两项操作之一:您的函数可以获取值并将其传递给FinalWindow ,或者可以将自身传递给FinalWindow并让FinalWindow获得所需的值。

Passing the individual values 传递个人价值观

For the first case, you need to define FinalWindow to take the values as parameters: 对于第一种情况,您需要定义FinalWindow以将值作为参数:

def FinalWindow(first, last):
    ...

Next, have do_order get the values and call the function: 接下来,让do_order获取值并调用函数:

def do_order(self):
    first_name = self.EntryFieldFN.get()
    surname = self.EntryFieldSN.get()
    window = FinalWindow(first_name, surname)

Passing the class instance 传递类实例

Instead of passing the values, you can pass the instance of Till to FinalWindow . 您可以将Till实例传递给FinalWindow而不是传递值。

First, modify FinalWindow to accept a single parameter, which is a instance of Till . 首先,修改FinalWindow以接受单个参数,该参数是Till的实例。 It can then use this instance to get the data it needs. 然后,它可以使用此实例获取所需的数据。

def FinalWindow(till):
    first_name = till.EntryFieldFN.get()
    surname = till.EntryFieldSN.get()
    ...

Next, modify do_order to simply pass itself to the function: 接下来,修改do_order以将自身简单地传递给函数:

def do_order(self):
    window = FinalWindow(self)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM