【问题标题】:Creating two windows using Tkinter and getting a name from the second window使用 Tkinter 创建两个窗口并从第二个窗口获取名称
【发布时间】:2020-11-25 23:54:47
【问题描述】:

我正在尝试使用 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()

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

【问题讨论】:

    标签: python oop tkinter


    【解决方案1】:

    一般来说,您应该避免在tkinter 应用程序中多次调用Tk()。也几乎不需要多次致电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()
    

    【讨论】:

      猜你喜欢
      • 2021-01-22
      • 1970-01-01
      • 1970-01-01
      • 2011-11-29
      • 2013-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多