簡體   English   中英

Python 3 ttk.Spinbox 格式選項

[英]Python 3 ttk.Spinbox format option

import tkinter as tk
import tkinter.ttk as ttk


root = tk.Tk()
style = ttk.Style()
style.theme_use('vista')

spinbox = ttk.Spinbox(root, from_=0, to=100, increment=5, format='%10.2f')
spinbox.set('{:10.2f} %'.format(0))  # default value

spinbox.pack()

root.minsize(400, 100)  # make window larger for ease of finding for this simple example
root.mainloop()

我想在ttk.Spinbox選項format='%10.2f' 中添加文字百分比符號。 因此,當您增加或減少值時,值后總會顯示一個 % 符號。 這似乎很難實現,我認為是我錯過了非常簡單/顯而易見的東西。 您可以在此處添加任何字符串並且它可以工作,但它不適用於文字 % 符號,因為提供給選項格式的字符串值包含它需要具有的 % 符號。

我嘗試的第一件事是轉義我想顯示的 % 符號,但它不起作用,例如: format='%10.2f\\\\%'

我已經在格式選項中嘗試了我能想到的所有內容,但我無法顯示 % 符號。 這不是一個真正的問題,但如果有人知道解決方案會很好,謝謝。

您可以將ttk.Spinbox子類ttk.Spinbox以更改其行為,以便在Spinbox條目中的單元旁邊顯示所需的格式:

import tkinter as tk
import tkinter.ttk as ttk


class FormattedSpinbox(ttk.Spinbox):
    """A ttk.Spinbox that displays a float with 2 decimals,
    alongside a '%' character unit
    """
    def __init__(self, master, **kwargs):
        kwargs['command'] = self.command
        super().__init__(master, **kwargs)
    def set(self, value):
        super().set(value)
        self.command()
    def get(self):
        return float(super().get().strip().split()[0])
    def command(self):
        value = self.get()
        self.delete(0, tk.END)
        self.insert(0, f'{float(value): 10.2f} %')


root = tk.Tk()

spinoptions = {'from_': 0, 'to': 100, 'increment': 5}
spinbox = FormattedSpinbox(root, **spinoptions)
spinbox.set(0)  # default value
spinbox.pack()

root.minsize(400, 100)
root.mainloop()

小部件如下所示:

在此處輸入圖片說明

或者,如果您想對格式進行參數化,則可以這樣做。 注意str(value).format(format)並不完全等同於f'{float(value): 10.2f} %') ; 前者不會添加空格來填充所需的寬度,並且如果該值具有足夠的精度,則小數位數至少為1,直到所需的數字為止。

import tkinter as tk
import tkinter.ttk as ttk


class FormattedSpinbox(ttk.Spinbox):
    """A ttk.Spinbox that displays a float with 2 decimals,
    alongside a '%' character unit
    """
    def __init__(self, master, **kwargs):
        kwargs['command'] = self.command
        super().__init__(master, **kwargs)
    def set(self, value):
        super().set(value)
        self.command()
    def get(self):
        return float(super().get().strip().split()[0])
    def command(self):
        value = self.get()
        self.delete(0, tk.END)
        svalue = str(value).format(format)
        self.insert(0, f'{svalue} %')


root = tk.Tk()

spinoptions = {'from_': 0, 'to': 100, 'increment': 5, 'format':'%10.2f'}
spinbox = FormattedSpinbox(root, **spinoptions)
spinbox.set(0)  # default value
spinbox.pack()

root.minsize(400, 100)
root.mainloop()

現在,小部件的外觀為:

在此處輸入圖片說明

因此,我安裝了Python 3.7.3,並找到了解決方案。 您必須在格式字符串中使用%%才能獲得原義的% 但是,通過spinbox.set(0.0)設置初始值並不會自動應用該格式,盡管文檔說可以。

我想制作一個當用戶在框中輸入或單擊旋轉按鈕時有效的方法。 它不是最精簡的,但似乎運行良好。

class FormattingSpinBox(ttk.Spinbox):

    def __init__(self, master, **kwargs):
        super().__init__(master, from_=0, to=100, command=self.command, **kwargs)
        self.displayValue = 2.5
        self.registerValidation()

    def registerValidation(self):
        self.configure(validate='all', validatecommand=(self.register(self.validation), '%i', '%P', '%s', '%V'))

    def validation(self, index, text, previousText, eventType):
        if eventType == 'focusin':
            self.focusInValidation(text)
            return True

        if eventType == 'key':

            if int(index) >= len(text) - 1:
                self.focusInValidation(previousText)

            return True

        return True

    def focusInValidation(self, text):

        self.icursor(len(text) - 2)
        self.displayValue = self.value

    @property
    def displayValue(self):
        return self.get()

    @property
    def value(self):
        try:
            return float(self.get()[:-2])
        except ValueError:
            return 0

    @displayValue.setter
    def displayValue(self, val):
        self.set(f'{float(val):4.2f} %')

    def command(self):
        self.displayValue = self.displayValue

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM