使用Tkinter创建两个窗口并从第二个窗口中获取名称

时间:2020-08-05 18:25:53

标签: python oop tkinter

我正在尝试使用Tkinter创建一个应用程序,该应用程序要求用户单击第一个窗口的按钮,然后将出现一个新窗口,在该窗口中将输入名称。 但是,当我尝试获取名称时,我总是以空字符串结尾。 这是我的代码:

from tkinter import *

class first_class(object):
    def __init__(self, window):
    
        self.window = window

        b1 = Button(window, text = "first_get", command = self.get_value_2)
        b1.grid(row = 0, column = 1)

    def get_value_2(self):
        sc = Tk()
        second_class(sc)
        sc.mainloop()

class second_class(object):
    def __init__(self, window):
        def get_value_1():
            print(self.name.get())
        self.window = window

        self.name = StringVar()
        self.e1 = Entry(window, textvariable = self.name)
        self.e1.grid(row = 0, column = 0)

        b1 = Button(window, text = "second_get", command = get_value_1)
        b1.grid(row = 0, column = 1)
        
window = Tk()
first_class(window)
window.mainloop()

我应该怎么做才能正确获得名字?

1 个答案:

答案 0 :(得分:4)

通常来说,您应该避免在Tk()应用程序中多次调用tkinter。几乎没有必要多次调用mainloop()

您的代码具有以下指示的更改,显示了如何执行此操作。请注意,我还重命名并重新格式化了一些内容,以便它更严格地遵循PEP 8 - Style Guide for Python Code中的建议-我强烈建议您阅读并开始遵循。

import tkinter as tk


class FirstClass(object):
    def __init__(self, window):
        self.window = window

        b1 = tk.Button(window, text="first_get", command=self.get_value_2)
        b1.grid(row=0, column=1)

    def get_value_2(self):
#        sc = tk.Tk()  # REMOVED
        SecondClass(self.window)  # CHANGED
#        sc.mainloop()  # REMOVED


class SecondClass(object):
    def __init__(self, window):
        self.window = window

        self.name = tk.StringVar()
        self.e1 = tk.Entry(window, textvariable=self.name)
        self.e1.grid(row=0, column=0)

        def get_value_1():
            print('self.name.get():', self.name.get())

        b1 = tk.Button(window, text="second_get", command=get_value_1)
        b1.grid(row=0, column=1)


window = tk.Tk()
FirstClass(window)
window.mainloop()