[英]Creating two windows using Tkinter and getting a name from the second window
I'm trying to create an app with Tkinter which requires the user to hit the button of the first window and then a new window will appear where they'll write their name.我正在尝试使用 Tkinter 创建一个应用程序,这需要用户点击第一个 window 的按钮,然后在他们写名字的地方会出现一个新的 window。 But i when i try to get the name, i always end up with an empty string.但是当我尝试获取名称时,我总是以一个空字符串结束。 Here's my code:这是我的代码:
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()
What should i do to get the name properly?我应该怎么做才能正确获得名称?
Generally speaking, you should avoid calling Tk()
more than once within a tkinter
application.一般来说,您应该避免在tkinter
应用程序中多次调用Tk()
。 It's also hardly ever necessary to call mainloop()
more than once.也几乎不需要多次调用mainloop()
。
Your code with the changes indicated below shows how to do this.您的代码具有如下所示的更改,显示了如何执行此操作。 Note that I also renamed and reformatted a few things so it follows the recommendations in PEP 8 - Style Guide for Python Code more closely — which I highly recommend you read and start following.请注意,我还重命名并重新格式化了一些内容,因此它更接近PEP 8 - Python 代码的样式指南中的建议 - 我强烈建议您阅读并开始遵循。
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.