【问题标题】:simple window with an enter field带有输入字段的简单窗口
【发布时间】:2022-01-02 16:44:20
【问题描述】:

我是一名新程序员,肯定有几个错误,但这应该不难发现。我需要创建一个简单的窗口,其中包含一个名为“Concorrente 1:”的字段和一个由名为 lacopertina() 的函数显示的输入字段。我不明白错误在哪里:

import tkinter as tk
from tkinter import *
from tkinter.ttk import *
from tkinter import ttk

class schermoiniziale(tk.Frame):
    def lacopertina():
        print(gio1)

        #return (tot1)   
        
    def __init__(self):
        global gio1 
        #tot1=0
        #schermo1=Tk()
        
        self.gio1=tk.StringVar()
        lab1=ttk.Label(self, text="Concorrente 1:") 
        lab1.pack()      
        ent1=ttk.Entry(self, textvariable=self.gio1)
        ent1.pack()
        pulsante = ttk.Button(self, text="Inizio", textvariable=self.gio1, command=self.lacopertina)
        pulsante.pack()
        
def main():
    schermoiniziale().mainloop()
if __name__== "__main__":
    main()

【问题讨论】:

  • 错误是什么?您需要发布错误的完整回溯。

标签: python tkinter window


【解决方案1】:

我建议您阅读一些有关 Python OOP 的教程。

我已经修改了您的代码,如下所示:

# avoid using wildcard import
import tkinter as tk
from tkinter import ttk

class schermoiniziale(tk.Frame):
    def __init__(self, master, **kw):
        # need to call __init__() of inherited class
        super().__init__(master, **kw)
        self.gio1 = tk.StringVar()
        lab1 = ttk.Label(self, text="Concorrente 1:")
        lab1.pack()
        ent1 = ttk.Entry(self, textvariable=self.gio1)
        ent1.pack()
        # removed textvariable=self.gio1 as I think you actually don't need it
        pulsante = ttk.Button(self, text="Inizio", command=self.lacopertina)
        pulsante.pack()

    def lacopertina(self):
        # use .get() to get the content of a StringVar
        print(self.gio1.get())

def main():
    # need to create the root window before creating other widget
    root = tk.Tk()
    # pass root window as the parent of the widget
    frame = schermoiniziale(root)
    frame.pack()
    # start the tkinter mainloop
    root.mainloop()

if __name__== "__main__":
    main()

【讨论】:

  • 非常感谢!
  • 对不起,@acw1668 还有一件事我不能做:我应该添加什么代码来切换到另一个窗口并显示 self.gio1.get() 的内容?非常感谢
  • @JamesGarofalo 最好为新问题提出另一个问题。
猜你喜欢
  • 2018-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多