2017-12-19 26 views
0

パーセントを表示するプログレスバーの中央にラベルを挿入するにはどうすればよいですか? 問題は、Pythonはラベルの背景の透明度をサポートしていないので、私はそれをどのように解決できるのか分かりません。パーセントラベルのプログレスバー?

+2

多分役立ちます(https://stackoverflow.com/questions/30180138/how- Tkinterを使用して透過ウィジェットを作成するにはどうすればいいですか?](https://stackoverflow.com/questions/17039481/how-to-create-transparent -widgets-using-tkinter) – davedwards

答えて

2

ttk.Styleを使用すると可能です。アイデアはバーの内側にラベルを追加するHorizontal.TProgressbarスタイル(縦ProgressBarのVertical.TProgressbarと同じことを行う)のレイアウトを変更することです:

通常Horizontal.TProgressbarレイアウト:追加のラベル付き

[('Horizontal.Progressbar.trough', 
    {'children': [('Horizontal.Progressbar.pbar', 
    {'side': 'left', 'sticky': 'ns'})], 
    'sticky': 'nswe'})] 

[('Horizontal.Progressbar.trough', 
    {'children': [('Horizontal.Progressbar.pbar', 
    {'side': 'left', 'sticky': 'ns'})], 
    'sticky': 'nswe'}), 
('Horizontal.Progressbar.label', {'sticky': 'nswe'})] 

次に、ラベルのテキストはstyle.configureで変更できます。ここで

はコードです:[?ラベルの背景はTkinterの中で透明にするようにする方法]

import tkinter as tk 
from tkinter import ttk 

root = tk.Tk() 

style = ttk.Style(root) 
# add label in the layout 
style.layout('text.Horizontal.TProgressbar', 
      [('Horizontal.Progressbar.trough', 
       {'children': [('Horizontal.Progressbar.pbar', 
           {'side': 'left', 'sticky': 'ns'})], 
       'sticky': 'nswe'}), 
       ('Horizontal.Progressbar.label', {'sticky': ''})]) 
# set initial text 
style.configure('text.Horizontal.TProgressbar', text='0 %') 
# create progressbar 
variable = tk.DoubleVar(root) 
pbar = ttk.Progressbar(root, style='text.Horizontal.TProgressbar', variable=variable) 
pbar.pack() 

def increment(): 
    pbar.step() # increment progressbar 
    style.configure('text.Horizontal.TProgressbar', 
        text='{:g} %'.format(variable.get())) # update label 
    root.after(200, increment) 

increment() 

root.mainloop() 

screenshot of the result

+0

非常に良い解決策!しかし、私の側の 'TypeError:getint()引数は23行目でfloatでなくstrでなければなりませんが、' variable'の型を 'StringVar'に変更すると期待通りに動作します! – CommonSense

+0

@CommonSenseフィードバックのおかげで、それは私のコンピュータ上でエラーを発生させない、私はプログレスバーの現在の値の形式に依存していると思う(あなたのケースではフロートのようです)。私は答えを修正します。 –

+0

@CommonSense 'DoubleVar'で動作しますか? –