本文介绍了Tkinter 格式化 DoubleVars 以显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 tk.DoubleVar() 在我的 tkinter GUI 中保存变量.

I use tk.DoubleVar() to hold variables in my tkinter GUI.

但是,如果我要显示百分比,例如,我想这样显示它们.例如

However, if I am displaying percentages, as an example, I would like to display them as such.For example

0.05 -> 5%

所以我可以格式化罚款,但是当我想使用 var.get() 时,使用非数字字符(例如%")似乎会导致问题,因为 5% 不是有效的数值.

So I can format the fine, but using non-numeric characters(such as '%') then seems to cause an issue when I want to use var.get() because 5% is not a valid numeric value.

无论如何要使用变量,在其中维护实际值,同时允许显示值的格式化版本?

Is there anyway to use variables, where the actual value is maintained, while allowing a formatted version of the value to be displayed?

推荐答案

您可以使用

print( "{:.0}%".format(var.get()*100) )

甚至使用特殊格式 {%} 而你不需要 *100%

or even using special formatting {%} and you don't need *100 and %

print( "{:.0%}".format(var.get()) )

(我添加了 :.0 来显示 5% 而不是 5.00%)

(I add :.0 to display 5% instead 5.00%)

如果您想要同时拥有值和格式化字符串,您可以使用方法 ie 创建类.to_string() 将其作为字符串获取.

If you want to have both - value and formatted string - you could create class with method ie. to_string() to get it as string.

import tkinter as tk

class PercentVar(tk.DoubleVar):

    def to_string(self):
        return "{:.0%}".format(self.get())

# ---

root = tk.Tk()

myvar = PercentVar(value=0.05)

print('value:', myvar.get())
print('string:', myvar.to_string())

或者类可能有方法 __str__ 可以在您 print() 或使用 str() 时自动将字符串转换为格式化版本 - 但是我不知道 tkinter 是否不使用正常值 PY_VAR0 来识别对象,而使用 __str__ 只会产生问题.


Or class may have method __str__ to automatically convert string to formatted version when you print() it or use str() - but I don't know if tkinter doesn't uses normal value PY_VAR0 to recognize object and using __str__ can makes only problem.

import tkinter as tk

class PercentVar(tk.DoubleVar):

    def __str__(self):
        return "{:.0%}".format(self.get())

# ---

root = tk.Tk()

myvar = PercentVar(value=0.05)

print('value:', myvar.get())
print('string:', myvar)
print('string: ' + str(myvar))
print('string: {}'.format(myvar))
print(f'string: {myvar}')

要将它与小部件一起使用,它将使用 trace

import tkinter as tk

# --- classes ---

class PercentVar(tk.DoubleVar):

    def to_string(self):
        return "{:.0%}".format(self.get())

# --- functions ---

def label_update(a, b, c):
    label["text"] = myvar.to_string()

# --- main ---

root = tk.Tk()

myvar = PercentVar()

label = tk.Label(root)  # without text and textvariable
label.pack()

myvar.trace('w', label_update)  # run `label_update` when `myvar` change value
myvar.set(0.05)  # set value after `trace`

root.mainloop()

但是同样可以只使用 DoubleVar

import tkinter as tk

# --- functions ---

def label_update(a, b, c):
    label["text"] = "{:.0%}".format(myvar.get())

# --- main ---

root = tk.Tk()

myvar = tk.DoubleVar()

label = tk.Label(root)  # without text and textvariable
label.pack()

myvar.trace('w', label_update)  # run `label_update` when `myvar` change value
myvar.set(0.05)  # set value after `trace`

root.mainloop()

我创建了 FormatLabel 类,它在开始时获取额外的参数 format 来格式化显示的文本.但是它没有功能以后用 config(format=...)["format"] = ...


I made class FormatLabel which gets extra argument format at start to format displayed text. But it has no function to changed it later with config(format=...) or ["format"] = ...

没有 format 它就像普通的 Label(它使用格式 '{}')但是你可以设置 ie fomat="{:.0%}" 显示 10% 而不是 0.1.您甚至可以使用 format="Today: {:.0%} or more" 来显示 "Today: 10% or more"

Without format it works like normal Label (it uses format '{}') but you can set i.e fomat="{:.0%}" to display 10% instead 0.1. You can even uses format="Today: {:.0%} or more" to display "Today: 10% or more"

import tkinter as tk

# --- class ---

class FormatLabel(tk.Label):

    def __init__(self, master=None, cnf={}, **kw):

        # default values
        self._format = '{}'
        self._textvariable = None

        # get new format and remove it from `kw` so later `super().__init__` doesn't use them (it would get error message)
        if 'format' in kw:
            self._format = kw['format']
            del kw['format']

        # get `textvariable` to assign own function which set formatted text in Label when variable change value
        if 'textvariable' in kw:
            self._textvariable = kw['textvariable']
            self._textvariable.trace('w', self._update_text)
            del kw['textvariable']

        # run `Label.__init__` without `format` and `textvariable`
        super().__init__(master, cnf={}, **kw)

        # update text after running `Label.__init__`
        if self._textvariable:
            #self._update_text(None, None, None)
            self._update_text(self._textvariable, '', 'w')

    def _update_text(self, a, b, c):
        """update text in label when variable change value"""
        self["text"] = self._format.format(self._textvariable.get())

# --- main ---

root = tk.Tk()

myvar = tk.DoubleVar(value=0.05)

#label = FormatLabel(root, textvariable=myvar, format="Today: {:.0%} and growing")
label = FormatLabel(root, textvariable=myvar, format="{:.0%}")
label.pack()

myvar.set(0.1)

root.mainloop()

这篇关于Tkinter 格式化 DoubleVars 以显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 22:17