在 tkinter 中的函数内将 StringVar 对象从 Entry 传递到 Label [英] Passing StringVar object from Entry to Label within functions in tkinter

查看:32
本文介绍了在 tkinter 中的函数内将 StringVar 对象从 Entry 传递到 Label的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力让它工作,每次我改变一些东西时我都会收到另一个错误.我一直在尝试创建一个带有函数的输入框,然后将输入框中的变量放入一个标签中,该标签是通过按下按钮创建的.当我尝试这样做时,经常出现此错误.

Hi I've been struggling to get this to work, each time i change something I receive another error. I've been trying to create an entry box with a function and then get the variable from the entry box into a label, created by a button press. When I tried to do this often this error came up.

TypeError: get() 缺少 1 个必需的位置参数:'self'

然后我将 self 放在方法括号中.

I then put self in in the method brackets.

command = lambda: x.myFunc(self.my_variable.get(self))

然后是另一个错误,我不知道如何解决.

Then another error, which I'm not sure how to sort out.

AttributeError: 'My_Class' object has no attribute '_tk'

这是完整的代码,我是类和 self 的新手,所以欢迎任何更正.

Here's the full code, I'm new to classes and self, so any corrections are welcome.

from tkinter import *
import time

class My_Class:
    def start(self):
        self.root=Tk()
        self.my_variable=StringVar
        self.entry_box=Entry(self.root, textvariable=self.my_variable)
        self.entry_box.pack()
        self.button=Button(self.root,text="Pass variable now",
         command=lambda:x.myFunc(self.my_variable.get(self)))
        self.button.pack()

def myFunc(self,my_variable):
    self.lab=Label(self.root,text=self.my_variable)
    self.lab.pack()

x=My_Class()
x.start()

推荐答案

If you make myFunc 一个方法 if 类(你可能正在尝试这样做;很难知道,因为你的缩进是错误),您不必将任何内容传递给 myFunc.该函数可以访问类中的所有内容,因此可以在需要时获取所需内容.这让您无需使用 lambda,这有助于降低复杂性.

If you make myFunc A method if the class (which you might be trying to do; it's hard to know because your indentation is wrong), you don't have to pass anything to myFunc. That function has access to everything in the class, so it can get what it needs, when it needs it. That lets you eliminate the use of lambda, which helps reduce complexity.

此外,您通常根本不需要 StringVar,这只是要跟踪的另一件事.但是,如果您真的需要标签和条目来显示完全相同的数据,让它们共享相同的文本变量,文本会自动更新,而无需调用函数,或从小部件获取值,或设置值 n标签.

Also, you normally don't need a StringVar at all, it's just one more thing to keep track of. However, if you really need the label and entry to show exactly the same data, have them share the same textvariable and the text is updated automatically without you having to call a function, or get the value from the widget, or set the value n the label.

这是一个没有使用 StringVar 的例子:

Here's an example without using StringVar:

class My_Class:
    def start(self): 
        ...
        self.entry_box = Entry(self.root)
        self.button = Button(..., command = self.myFunc)
        ...

    def myFunc(self):
        s = self.entry_box.get()
        self.lab = Label(..., text = s)
        ...

这篇关于在 tkinter 中的函数内将 StringVar 对象从 Entry 传递到 Label的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆