首页 > 解决方案 > 是否可以从 topview tkinter 窗口获取输入并从主 tk 窗口中检索保存的输入字段值

问题描述

该程序由类组成,我试图在函数中使用 tkinter 顶视图,以便在调用它时能够从 tkinter import 检索主类的入口字段值

from PIL import Image, ImageTk

下面是处理从一个类转换到另一个类的驱动程序代码

class SeaofBTCapp(Tk):
    def __init__(self, *args, **kwargs):
        Tk.__init__(self, *args, **kwargs)
        container = Frame(self)
        container.pack(side="top", fill="both", expand=True)

        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)
        self.frames = {}

        for F in (
                WelcomePage, Register_new_user):  # ,PageThree,PageFour):
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")
        self.show_frame(WelcomePage)

    # def show_frame(self, cont):
    #     frame = self.frames[cont]
    #     frame.tkraise()

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()
        frame.update()
        frame.event_generate("<<show_frame>>")

    def get_page(self, cont):
        for page in self.frames.values():
            if str(page.__class__.__name__) == cont:
                return page
        return None


class Register_new_user(object):
    pass

下面是程序的入口点,是要显示的第一页

class WelcomePage(Frame):

    def __init__(self, parent, controller):
        Frame.__init__(self, parent)

        # self.bind("<<show_frame>>", self.main_prog)

        def resize_image(event):
            global photo
            new_width = event.width
            new_height = event.height

            image = copy_of_image.resize((new_width, new_height))
            photo = ImageTk.PhotoImage(image)

            label.config(image=photo)
            label.image = photo  # avoid garbage collection

        def pin_input():
            top = Toplevel()
            top.geometry("180x100")
            top.title("toplevel")
            l2 = Label(top, text="This is toplevel window")
            global entry_1
            global password
            password = StringVar
            entry_1 = None

            def cleartxtfield():
                global password
                new = "3"
                password.set(new)

            # #############  Function to parse for only numerical input
            def validate(input):
                if input.isdigit():
                    return True
                elif input == "":
                    return True
                else:
                    return False

            def enternumber(x):
                global entry_1
                setval = StringVar()
                setval = str(x)
                # print(setval)
                entry_1.insert(END, setval)

            entry_1 = Entry(top, textvariable=password, width=64, show='*')
            entry_1.place(x=200, y=100)
            entry_1.focus()

            reg = top.register(validate)
            entry_1.config(validate="key", validatecommand=(reg, '%P'))

            def getcreds():
                # check if four digit entered and is not empty
                global passwd
                passwd = password.get()
                print(f"The Credentials are {passwd}")

            def funcbackspace():
                length = len(entry_1.get())
                entry_1.delete(length - 1, 'end')

            def killwindow():
                # when the user quits it should clear all the data input fields filled in in the previous steps. and should display information that it is about to quit in a few seconds

                command = top.destroy()
                # Label(top,text="Goodbye\n (Closing in 2 seconds)")
                top.after(2000, top.quit())

            cancel = Button(top, width=8, height=3, text="Cancel", bg="red", fg="black", command=killwindow)
            cancel.place(x=220, y=150)
            backspace = Button(top, width=8, height=3, text="Backspace", bg="red", fg="black", command=funcbackspace)
            backspace.place(x=500, y=150)

            # ----number Buttons------
            def enternumber(x):
                global entry_1
                setval = StringVar()
                setval = str(x)
                # print(setval)
                entry_1.insert(END, setval)

            btn_numbers = []
            for i in range(10):
                btn_numbers.append(
                    Button(top, width=8, height=3, text=str(i), bd=6, command=lambda x=i: enternumber(x)))
            btn_text = 1
            for i in range(0, 3):
                for j in range(0, 3):
                    btn_numbers[btn_text].place(x=220 + j * 140, y=250 + i * 100)
                    btn_text += 1

            btn_zero = Button(top, width=15, height=2, text='0', bd=5, command=lambda x=0: enternumber(x))
            btn_zero.place(x=330, y=550)
            clear = Button(top, text="Clear", bg="green", fg="white", width=8, height=3, command=cleartxtfield)
            clear.place(x=220, y=550)
            okbtn = Button(top, text="Enter", bg="green", fg="black", width=8, height=3, command=getcreds)
            okbtn.place(x=500, y=550)
            val = getcreds()
            print("The value to be returned is %s" % val)
            return val

        password = pin_input()
        print("Gotten password is %s" % password)
        copy_of_image = Image.open("image.png")
        photoimage = ImageTk.PhotoImage(copy_of_image)

        label = Label(self, image=photoimage)
        label.place(x=0, y=0, relwidth=1, relheight=1)
        label.bind('<Configure>', resize_image)

        top_left_frame = Frame(self, relief='groove', borderwidth=2)
        top_left_frame.place(relx=1, rely=0.1, anchor=NE)
        center_frame = Frame(self, relief='raised', borderwidth=2)
        center_frame.place(relx=0.5, rely=0.75, anchor=CENTER)
        Button(top_left_frame, text='REGISTER', bg='grey', width=14, height=1,
               command=lambda: controller.show_frame(Register_new_user)).pack()
        Button(center_frame, text='ENTER', fg='white', bg='green', width=13, height=2,
               command=lambda: controller.show_frame(Register_new_user)).pack()


if __name__ == '__main__':
    app = SeaofBTCapp()
    app.title("Password return on topview window")
    width = 1000
    height = 700
    screenwidth = app.winfo_screenwidth()
    screenheight = app.winfo_screenheight()
    alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
    app.geometry(alignstr)
    # app.resizable(width=False, height=False)
    app.resizable(width=True, height=True)

    app.mainloop()

标签: python-3.xtkinter

解决方案


如果我理解正确,您想在对话框中输入密码,然后在关闭对话框时从对话框中获取密码。

查看effbot 的Dialog Windows以了解有关创建对话窗口的讨论。

这是一个如何实现简单对话框的示例:

from tkinter import *
from tkinter import simpledialog
 
class MyDialog(simpledialog.Dialog):
 
    def body(self, master):
        '''create dialog body.
 
        return widget that should have initial focus.
        This method should be overridden, and is called
        by the __init__ method.'''
 
        Label(master, text='Value:').grid(row=0)
        self.e1 = Entry(master)
        self.e1.grid(row=0, column=1)
 
        return self.e1      # initial focus
 
    def apply(self):
        '''process the data
 
        This method is called automatically to process the data, *after*
        the dialog is destroyed. By default, it does nothing.'''
 
        value = self.e1.get()
        self.result = value
 
    def validate(self):
        '''validate the data
 
        This method is called automatically to validate the data before the
        dialog is destroyed. By default, it always validates OK.'''
 
        return 1 # override
 
    def buttonbox(self):
        '''add standard button box.
 
        override if you do not want the standard buttons
        '''
 
        box = Frame(self)
 
        w = Button(box, text="OK", width=10, command=self.ok, default='active')
        w.pack(side='left', padx=5, pady=5)
        w = Button(box, text="Cancel", width=10, command=self.cancel)
        w.pack(side='left', padx=5, pady=5)
 
        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.cancel)
 
        box.pack()
 
if __name__ == '__main__':
    root = Tk()
    root.geometry('200x100+800+50')
 
    def do():
        d = MyDialog(root)
        print(d.result)
 
    b = Button(root, text='Go!', width=10, command=do)
    b.pack(expand=True)

这回答了你的问题吗?


推荐阅读