本文介绍了tkinter 的变量和 StringVar() 有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import tkinter as tk
a = "hi"
print(a)
a1 = tk.StringVar()
a1.set("Hi")
print(a1)

输出:

hi ##(Output from first print function)

AttributeError: 'NoneType' object has no attribute '_root' (Output from second print function)

我的问题:

上面代码中的 aa1 之间有什么区别及其用例.为什么 a1 报错?

My question:

What is the difference between a and a1 in above code and their use-cases. Why a1 is giving error?

推荐答案

StringVar() 用于编辑小部件的文本

A StringVar() is used to edit a widget's text

例如:

import tkinter as tk


root = tk.Tk()
my_string_var = tk.StringVar()
my_string_var.set('First Time')
tk.Label(root, textvariable=my_string_var).grid()
root.mainloop()

将有一个带有标签的输出,上面写着 First Time注意:使用字符串变量时必须使用textvariable

Will have an output with a label saying First TimeNOTE:textvariable has to be used when using string variables

还有这段代码:

import tkinter as tk

def change():
    my_string_var.set('Second Time')

root = tk.Tk()
my_string_var = tk.StringVar()
my_string_var.set('First Time')
tk.Label(root, textvariable=my_string_var).grid()
tk.Button(root, text='Change', command=change).grid(row=1)
root.mainloop()

生成一个标签,上面写着 First Time 和一个按钮,可以很容易地将其更改为 Second Time.

Produces a label saying First Time and a button to very easily change it to Second Time.

普通变量做不到,只有tkinter的StringVar()

A normal variable can't do this, only tkinter's StringVar()

希望这能回答您的问题!

Hopes this answers your questions!

这篇关于tkinter 的变量和 StringVar() 有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 07:38