Python 使用Tkinter创建两个窗口并从第二个窗口获取名称
我正在尝试用Tkinter创建一个应用程序,它要求用户点击第一个窗口的按钮,然后出现一个新窗口,在那里他们将写下自己的名字。 但是当我试图得到这个名字时,我总是得到一个空字符串。 这是我的密码:Python 使用Tkinter创建两个窗口并从第二个窗口获取名称,python,oop,tkinter,Python,Oop,Tkinter,我正在尝试用Tkinter创建一个应用程序,它要求用户点击第一个窗口的按钮,然后出现一个新窗口,在那里他们将写下自己的名字。 但是当我试图得到这个名字时,我总是得到一个空字符串。 这是我的密码: from tkinter import * class first_class(object): def __init__(self, window): self.window = window b1 = Button(window, text =
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()
我应该怎么做才能正确获得名称?一般来说,您应该避免在tkinter应用程序中多次调用Tk。几乎不需要多次调用mainloop 您的代码以及下面指示的更改显示了如何执行此操作。请注意,我还重命名并重新格式化了一些内容,以便更紧密地遵循中的建议-我强烈建议您阅读并开始遵循这些建议
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()
一般来说,应该避免在tkinter应用程序中多次调用Tk。几乎不需要多次调用mainloop 您的代码以及下面指示的更改显示了如何执行此操作。请注意,我还重命名并重新格式化了一些内容,以便更紧密地遵循中的建议-我强烈建议您阅读并开始遵循这些建议
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()