Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/iphone/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 是否可以从topview tkinter窗口获取输入,并从master tk窗口中检索保存的输入字段值_Python 3.x_Tkinter - Fatal编程技术网

Python 3.x 是否可以从topview tkinter窗口获取输入,并从master tk窗口中检索保存的输入字段值

Python 3.x 是否可以从topview tkinter窗口获取输入,并从master tk窗口中检索保存的输入字段值,python-3.x,tkinter,Python 3.x,Tkinter,该程序由类组成,我试图在函数中使用tkinter topview,以便在调用它时能够检索主类的entryfield值 从tkinter进口 from PIL import Image, ImageTk 下面是处理从一个类到另一个类转换的驱动程序代码 class SeaofBTCapp(Tk): def __init__(self, *args, **kwargs): Tk.__init__(self, *args, **kwargs) container

该程序由类组成,我试图在函数中使用tkinter topview,以便在调用它时能够检索主类的entryfield值 从tkinter进口

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
SeaOfBTApp(Tk)类:
定义初始化(self,*args,**kwargs):
Tk.\uuuuu初始值(self,*args,**kwargs)
容器=框架(自身)
container.pack(side=“top”,fill=“both”,expand=True)
container.grid_rowconfigure(0,权重=1)
container.grid\u column配置(0,权重=1)
self.frames={}
为F英寸(
欢迎第页,注册新用户:#,第三页,第四页):
框架=F(容器,自身)
self.frames[F]=帧
frame.grid(行=0,列=0,sticky=“nsew”)
自我展示框架(WelcomePage)
#def显示画面(自身,续):
#帧=自身帧[续]
#frame.tkraise()
def显示画面(自身,续):
帧=自身帧[续]
frame.tkraise()
frame.update()
frame.event_generate(“”)
def get_页面(自身,续):
对于self.frames.values()中的页面:
如果str(页码、类别、名称)=续:
返回页
一无所获
类注册\新\用户(对象):
通过
下面是程序的入口点,是要显示的第一页

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()
class Welcome页面(框架):
定义初始化(自、父、控制器):
帧。\uuuu初始化(自,父)
#self.bind(“,self.main\u prog)
def resize_图像(事件):
全球照片
新建宽度=event.width
新高度=事件高度
图像=复制图像。调整大小((新宽度,新高度))
photo=ImageTk.PhotoImage(图像)
label.config(image=photo)
label.image=photo#避免垃圾收集
def引脚_输入()
顶层=顶层()
顶部几何图形(“180x100”)
顶级标题(“顶级”)
l2=标签(顶部,text=“这是顶层窗口”)
全球项目1
全局密码
密码=StringVar
条目1=无
def cleartxtfield():
全局密码
new=“3”
密码设置(新)
#函数,用于仅解析数字输入
def验证(输入):
如果input.isdigit():
返回真值
elif输入==“”:
返回真值
其他:
返回错误
def入口编号(x):
全球项目1
setval=StringVar()
setval=str(x)
#打印(setval)
条目1.插入(结束,设定值)
entry_1=entry(顶部,textvariable=password,宽度=64,show='*'))
入口位置(x=200,y=100)
条目_1.焦点()
reg=顶部寄存器(验证)
条目_1.config(validate=“key”,validatecommand=(reg,'%P'))
def getcreds():
#检查输入的四位数字是否为空
全局密码
passwd=password.get()
打印(f“凭证为{passwd}”)
def funcbackspace():
length=len(条目_1.get())
条目_1.删除(长度-1,“结束”)
def killwindow():
#当用户退出时,应清除前面步骤中填写的所有数据输入字段。并应显示几秒钟后即将退出的信息
command=top.destroy()
#标签(顶部,text=“再见\n(2秒后关闭)”)
top.after(2000,top.quit())
取消=按钮(顶部,宽度=8,高度=3,text=“取消”,bg=“红色”,fg=“黑色”,命令=killwindow)
取消。放置(x=220,y=150)
退格=按钮(顶部,宽度=8,高度=3,text=“退格”,bg=“红色”,fg=“黑色”,命令=退格)
退格位置(x=500,y=150)
#----数字按钮------
def入口编号(x):
全球项目1
setval=StringVar()
setval=str(x)
#打印(setval)
条目1.插入(结束,设定值)
btn_编号=[]
对于范围(10)内的i:
btn_number.append(
按钮(顶部,宽度=8,高度=3,文本=str(i),bd=6,命令=lambda x=i:enternumber(x)))
btn_text=1
对于范围(0,3)内的i:
对于范围(0,3)内的j:
btn_编号[btn_文本]。位置(x=220+j*140,y=250+i*100)
btn_text+=1
btn_zero=按钮(顶部,宽度=15,高度=2,文本=0',bd=5,命令=lambda x=0:enternumber(x))
btn_零位(x=330,y=550)
清除=按钮(顶部,text=“清除”,bg=“绿色”,fg=“白色”,宽度=8,高度=3,命令=cleartxtfield)
清除。放置(x=220,y=550)
okbtn=按钮(顶部,text=“回车”,bg=“绿色”,fg=“黑色”,宽度=8,高度=3,命令=getcreds)
确定地点(x=500,y=550)
val=getcreds()
打印(“要返回的值为%s”%val)
返回值
密码=pin_输入()
打印(“获取的密码为%s”%password)
复制图片=image.open(“image.png”)
photoimage=ImageTk.photoimage(图像的副本)
标签=标签(自我,图像=照片图像)
label.place(x=0,y=0,relwidth=1,relheight=1)
label.bind(“”,调整图像大小)
左上角框架=框架(自身,浮雕=凹槽,边框宽度=2)
左上角框架位置(relx=1,RELn=0.1,锚定=NE)
中心框架=框架(自、浮雕=凸起、边框宽度=2)
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)