输入所有值后如何从类中获取输出

时间:2018-07-29 07:08:24

标签: python tkinter

from tkinter import *

app = Tk()
app.title("First Software")
app.minsize(500, 500)

#For Input Declaration
UserName = StringVar()
pass1 = IntVar()

class Functions:
    def username(self, UserName):
        self.UserName = Username
        print(UserName.get())
    def password(self, pass1):
        self.pass1 = pass1
        print(pass1.get())

#---Label---
label = Label(text='Enter any Number between 1 and 100...').pack()

#---Entry---
entry = Entry(app, textvariable=UserName).pack()
entry1 = Entry(app, textvariable=pass1).pack()

#---Buttton---
button = Button(text='Submit', command=Functions).pack()

app.mainloop()

运行此代码后,如何使用此方法获得用户名和密码的单独输入。我现在有点困惑!

1 个答案:

答案 0 :(得分:0)

command=Functions告诉Tkinter在按下“提交”按钮时创建您的Functions类的实例。但是它没有告诉它调用Functions内部定义的函数。但是,该类定义有点奇怪,您实际上并不需要一个类来包含这些函数。相反,我们可以编写一个简单的函数来获取UserNamepass1的值并打印出来。

我对您的代码进行了其他一些小的更改。

import tkinter as tk

app = tk.Tk()
app.title("First Software")
#app.minsize(500, 500)

#For Input Declaration
UserName = tk.StringVar()
pass1 = tk.IntVar()

def print_entries():
    print('User name:', UserName.get())
    print('Password:', pass1.get())

tk.Label(app, text='User name.').pack()
entry = tk.Entry(app, textvariable=UserName)
entry.pack()

tk.Label(app, text='Password\nEnter any Number between 1 and 100').pack()
entry1 = tk.Entry(app, textvariable=pass1)
entry1.pack()

tk.Button(app, text='Submit', command=print_entries).pack()

app.mainloop()

此代码实际上不需要名称entryentry1,但是我保留了它们,以防您要添加确实需要按名称引用这些小部件的代码。

请注意,您应该这样做

entry = Entry(app, textvariable=UserName).pack()

.pack方法返回None,因此上述语句将None的值分配给entry。相反,我们这样做

entry = tk.Entry(app, textvariable=UserName)
entry.pack()

这会将新的Entry小部件分配给名称entry,然后调用其.pack方法将其打包到窗口中。


如果愿意,可以将代码包装在一个类中,但是我不会打扰像这样的简单GUI。但这是做到这一点的一种方法:

import tkinter as tk

class App:
    def __init__(self):
        root = tk.Tk()
        root.title("First Software")
        #root.minsize(500, 500)

        #For Input Declaration
        self.UserName = tk.StringVar()
        self.pass1 = tk.IntVar()

        tk.Label(root, text='User name.').pack()
        entry = tk.Entry(root, textvariable=self.UserName)
        entry.pack()

        tk.Label(root, text='Password\nEnter any Number between 1 and 100').pack()
        entry1 = tk.Entry(root, textvariable=self.pass1)
        entry1.pack()

        tk.Button(root, text='Submit', command=self.print_entries).pack()

        root.mainloop()

    def print_entries(self):
        print('User name:', self.UserName.get())
        print('Password:', self.pass1.get())

App()