[Python] [Tkinter] добавление флага, чтобы сделать передний план метки красным в цикле? - PullRequest
0 голосов
/ 25 сентября 2018

Так что я не могу понять, как решить эту дилемму, которая у меня есть.У меня есть простой сценарий, который в основном печатает 5 этикеток, каждая распечатывается 1 за другой с паузой в 2 секунды.

Что я хотел сделать, так это в основном выделить текущую работающую этикетку красным цветом, а затем, когда2-я этикетка распечатывает, передний план 1-й этикетки должен вернуться в «черный» и так далее.Таким образом, последний ярлык должен быть красным, а предыдущий - черным.

По сути, цель этого в том, чтобы у меня был скрипт автоматизации, написанный на python для тестирования Android TV, и я хочу сделатьпростой графический интерфейс для этого.Я хочу выделить текущий тестовый пример, который выполняется.После выполнения функции (тестового примера) я хочу, чтобы она стала черной.

Код ниже.

from tkinter import *
from tkinter import ttk
import tkinter.font as tkFont
import time

class SampleTkinterLoop:

    def __init__(self, master):
        # Initialize master as the Tk() instance
        self.master = master
        master.title("Loop Tests")
        master.geometry("768x480")

        # Create main frame as app
        self.app = ttk.Frame(root)
        self.app.pack(fill="both", expand=True)

        # Create a custom font
        self.mainFont = tkFont.Font(family="Helvetica", size=12)

        # Initialize flags for BG and FG change
        self.bgCounter = 0

    def test1(self):
        x = True # set fgChooser to True to make foreground red
        ttk.Label(
            self.app, text=f'Test case 1',
            background=self.bgChooser(),
            foreground=self.fgChooser(x),
            font=self.mainFont).pack()
        self.bgCounter += 1
        x = False # set it back to false to make foreround black
        root.update()  # allow window to catch up
        time.sleep(2)

    def test2(self):
        x = True # set fgChooser to True to make foreground red
        ttk.Label(
            self.app, text=f'Test case 2',
            background=self.bgChooser(),
            foreground=self.fgChooser(x),
            font=self.mainFont).pack()
        self.bgCounter += 1
        x = False # set it back to false to make foreround black
        root.update()  # allow window to catch up
        time.sleep(2)

    def test3(self):
        x = True # set fgChooser to True to make foreground red
        ttk.Label(
            self.app, text=f'Test case 3',
            background=self.bgChooser(),
            foreground=self.fgChooser(x),
            font=self.mainFont).pack()
        self.bgCounter += 1
        x = False # set it back to false to make foreround black
        root.update()  # allow window to catch up
        time.sleep(2)

    def test4(self):
        x = True # set fgChooser to True to make foreground red
        ttk.Label(
            self.app, text=f'Test case 4',
            background=self.bgChooser(),
            foreground=self.fgChooser(x),
            font=self.mainFont).pack()
        self.bgCounter += 1
        x = False # set it back to false to make foreround black
        root.update()  # allow window to catch up
        time.sleep(2)

    def test5(self):
        x = True # set fgChooser to True to make foreground red
        ttk.Label(
            self.app, text=f'Test case 5',
            background=self.bgChooser(),
            foreground=self.fgChooser(x),
            font=self.mainFont).pack()
        self.bgCounter += 1
        x = False # set it back to false to make foreround black
        root.update()  # allow window to catch up
        time.sleep(2)

    def repeatIt(self):
        for i in range(0, 5):
            # self.anotherLoop()
            self.test1()
            self.test2()
            self.test3()
            self.test4()
            self.test5()
            self.reset()
            root.update()
            time.sleep(1)
            print(i)

    def bgChooser(self):
        # make label background alternate to white and gray for easy reading
        if (self.bgCounter % 2) == 0:
            return str("#fff")
        return str("#ccc")

    def fgChooser(self, isActive=False):
        # this is where the  problem is, can't seem to find a way to make a flag for foreground color of label
        if isActive:
            return str("#a5120d")
        return str("#000")

    def reset(self):
        '''reset the UI'''
        for child in self.app.winfo_children():
            child.destroy()

root = Tk()
LoopTest = SampleTkinterLoop(root)
LoopTest.repeatIt()
root.mainloop()

Приведенный выше код делает всю метку красной, она не превращает предыдущую меткучерному.

1 Ответ

0 голосов
/ 25 сентября 2018

Вам не нужно использовать ttk для этой задачи.Это потому, что вы можете изменить цвет метки позже.
Например:
Импорт:

from tkinter import *  #<-- so you don't have to edit your full code
import tkinter as ttk     #<---
import tkinter.font as tkFont
import time

Вы можете редактировать свою test1 функцию так:

x = True 
xyz = ttk.Label(   #assign to a variable rather than packing <---
    self.app, text=f'Test case 1',
    background=self.bgChooser(),
    foreground=self.fgChooser(x),
    font=self.mainFont)
xyz.pack()   #pack later  <---
self.bgCounter += 1
x = False 
root.update()
time.sleep(2)
xyz.config(fg="black")   #change color after 2 sec  <---

Здесьэто пример кода:

from tkinter import *
import tkinter as ttk
import tkinter.font as tkFont
import time

class SampleTkinterLoop:

    def __init__(self, master):
        # Initialize master as the Tk() instance
        self.master = master
        master.title("Loop Tests")
        master.geometry("768x480")

        # Create main frame as app
        self.app = ttk.Frame(root)
        self.app.pack(fill="both", expand=True)

        # Create a custom font
        self.mainFont = tkFont.Font(family="Helvetica", size=12)

        # Initialize flags for BG and FG change
        self.bgCounter = 0

    def test1(self):
        x = True # set fgChooser to True to make foreground red
        xyz = ttk.Label(
            self.app, text=f'Test case 1',
            background=self.bgChooser(),
            foreground=self.fgChooser(x),
            font=self.mainFont)
        xyz.pack()
        self.bgCounter += 1
        x = False # set it back to false to make foreround black
        root.update()  # allow window to catch up
        time.sleep(2)
        xyz.config(fg="black")

    def test2(self):
        x = True # set fgChooser to True to make foreground red
        xyz = ttk.Label(
            self.app, text=f'Test case 2',
            background=self.bgChooser(),
            foreground=self.fgChooser(x),
            font=self.mainFont)
        xyz.pack()
        self.bgCounter += 1
        x = False # set it back to false to make foreround black
        root.update()  # allow window to catch up
        time.sleep(2)
        xyz.config(fg="black")

    def test3(self):
        x = True # set fgChooser to True to make foreground red
        xyz = ttk.Label(
            self.app, text=f'Test case 3',
            background=self.bgChooser(),
            foreground=self.fgChooser(x),
            font=self.mainFont)
        xyz.pack()
        self.bgCounter += 1
        x = False # set it back to false to make foreround black
        root.update()  # allow window to catch up
        time.sleep(2)
        xyz.config(fg="black")

    def test4(self):
        x = True # set fgChooser to True to make foreground red
        xyz = ttk.Label(
            self.app, text=f'Test case 4',
            background=self.bgChooser(),
            foreground=self.fgChooser(x),
            font=self.mainFont)
        xyz.pack()
        self.bgCounter += 1
        x = False # set it back to false to make foreround black
        root.update()  # allow window to catch up
        time.sleep(2)
        xyz.config(fg="black")

    def test5(self):
        x = True # set fgChooser to True to make foreground red
        xyz = ttk.Label(
            self.app, text=f'Test case 5',
            background=self.bgChooser(),
            foreground=self.fgChooser(x),
            font=self.mainFont)
        xyz.pack()
        self.bgCounter += 1
        x = False # set it back to false to make foreround black
        root.update()  # allow window to catch up
        time.sleep(2)
        xyz.config(fg="black")

    def repeatIt(self):
        for i in range(0, 5):
            # self.anotherLoop()
            self.test1()
            self.test2()
            self.test3()
            self.test4()
            self.test5()
            self.reset()
            root.update()
            time.sleep(1)
            print(i)

    def bgChooser(self):
        # make label background alternate to white and gray for easy reading
        if (self.bgCounter % 2) == 0:
            return str("#fff")
        return str("#ccc")

    def fgChooser(self, isActive=False):
        # this is where the  problem is, can't seem to find a way to make a flag for foreground color of label
        if isActive:
            return str("#a5120d")
        return str("#000")

    def reset(self):
        '''reset the UI'''
        for child in self.app.winfo_children():
            child.destroy()

root = Tk()
LoopTest = SampleTkinterLoop(root)
LoopTest.repeatIt()
root.mainloop()
...