到StringVar()绑定的tkinter项不起作用

2024-10-01 07:30:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个问题,我不知道为什么。。 此屏幕截图总结了所有需要的代码: Screenshot_Code

请不要寻找意义,我尽可能地修剪代码,只是为了显示问题

我的问题如下:

  • 如果我运行main.py
  • 然后根据“ui\u root.py”单击按钮
  • 然后在输入字段中输入一些文本,并根据“create_user.py”单击按钮
  • 那么我的print语句是空的,分别是StringVar()绑定不起作用

Bu如果我直接运行“create_user.py”(取消UiCreateUser()注释),那么我的print语句将精确打印我的输入小部件中的内容/文本

为什么??我不明白,如果有人能帮我,我将不胜感激。。提前谢谢

用于复制和粘贴的代码(对于阅读使用屏幕截图,可能比此更好):

main.py

from ui_root import UiRoot
app = UiRoot()
app.mainloop()

ui\u root.py

from tkinter import Tk, Button
from pixela_brain import PixelaBrain

class UiRoot(Tk):

    def __init__(self):
        super().__init__()
        self.brain = PixelaBrain()

        self.button = Button(self, text="Button", command=self.click)
        self.button.pack()

    def click(self):
        self.brain.create_user()

pixela\u brain.py

from popup_windows import create_user
import json


class PixelaBrain:
    def __init__(self):
        pass

    def create_user(self):
        self.new_user = create_user.UiCreateUser()

创建_user.py

from tkinter import Tk, Entry, Button, StringVar


class UiCreateUser(Tk):
    def __init__(self):
        super().__init__()

        # Entry
        self.entry_var = StringVar()
        self.entry = Entry(self, textvariable=self.entry_var)
        self.entry.pack()

        # Button
        self.button = Button(self, text="Click", command=self.btn_click)
        self.button.pack()

        self.mainloop()

    def btn_click(self):
        print(self.entry_var.get())


# UiCreateUser()

Tags: frompyimportselfinitdefcreatebutton
1条回答
网友
1楼 · 发布于 2024-10-01 07:30:59

这是一个“答案”,因为jasonharper的输入(在上面的评论中)解决了我的问题,我想结束这个问题

只需将类UiCreateUser(Tk)替换为类UiCreateUser(顶级)即可解决问题

非常感谢:)

相关问题 更多 >