繁体   English   中英

如何在 pysimplegui 中更改背景颜色?

[英]How do I change background color in pysimplegui?

我正在为我和一个朋友制作的病毒模拟开发 UI,我真的很难改变 UI 的背景颜色。 我从其中一个演示项目中获取了大部分代码,因为我无法弄清楚如何使用 pysimplegui 实现 matplotlib 所以有些事情我不完全理解,但通常使用 pysimplegui 它就像sg.theme="color更改主要背景颜色,但这次不起作用。非常感谢任何帮助,谢谢。

import PySimpleGUI as sg 
import numpy as np
import tkinter 

import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk

def draw_figure(canvas, fig):
    if canvas.children:
        for child in canvas.winfo_children():
            child.destroy()
    figure_canvas_agg = FigureCanvasTkAgg(fig, master=canvas)
    figure_canvas_agg.draw()
    figure_canvas_agg.get_tk_widget().pack(side='right', fill='both', expand=1)


# ------------------------------- PySimpleGUI CODE

layout = [
    [sg.Text("Population size: "), sg.Input(key="-POPULATIONSIZE-")],
    [sg.Text("Duration: "), sg.Input(key="-DURATION-")],
    [sg.Text("R Number: "), sg.Input(key="-RNUMBER-")],
    [sg.Text("Starting Infections: "), sg.Input(key="-STARTINGINFECTIONS-")],
    [sg.B('OK'), sg.B('Exit')],
    [sg.Canvas(key='controls_cv')],
    [sg.T('Figure:')],
    [sg.Column(
        layout=[
            [sg.Canvas(key='fig_cv',
                       size=(400 * 2, 400)
                       )]
        ],
        background_color='#DAE0E6',
        pad=(0, 0)
    )],
]

window = sg.Window('Virus Simulation', layout,)

while True:
    event, values = window.read()
    print(event, values)
    if event in (sg.WIN_CLOSED, 'Exit'):
        break
    elif event is 'OK':
        # ------------------------------- PASTE YOUR MATPLOTLIB CODE HERE
        plt.figure(1)
        fig = plt.gcf()
        DPI = fig.get_dpi()
        # ------------------------------- you have to play with this size to reduce the movement error when the mouse hovers over the figure, it's close to canvas size
        fig.set_size_inches(404 * 2 / float(DPI), 404 / float(DPI))
        # -------------------------------
        x = list(range(1, 100))
        y = list(range(1, 100))
        plt.plot(x, y, color="r")
        plt.title('Virus Infections Data')
        plt.xlabel('Time in Days')
        plt.ylabel('Infections')
        plt.grid()

        # ------------------------------- Instead of plt.show()
        draw_figure(window['fig_cv'].TKCanvas, fig,)


window.close()

您可以通过在layout下的以下参数中指定十六进制颜色代码来更改背景颜色:

background_color='#DAE0E6'

您可以使用像这样的颜色选择器https://htmlcolorcodes.com/color-picker/来获取您的颜色

您还可以使用:

window = sg.Window('Virus Simulation', layout, background_color='hex_color_code')

改变a的颜色 window object

我在两个方面有点困惑。

1 - 我在你的代码中没有看到对sg.theme()的调用,所以我不知道它在代码中的什么位置。 它放在哪里很重要。 始终尽早放置主题,绝对是在进行布局之前。 2 - 我不知道“这次不工作”是什么意思。 同样,更多的是需要查看完整的示例才能获得它。

您所说的正常工作的问题中的示例代码格式很奇怪,所以一定是被打乱了。

问题显示: sg.theme="color

但正如 Jason 指出的那样,传递给sg.theme()的值不仅仅是一种颜色。 “主题名称公式”在此处的主要 PySimpleGUI 文档中进行了描述 - https://pysimplegui.readthedocs.io/en/latest/#theme-name-formula 如果进入该部分时遇到问题,请按以下说明进行操作:

Theme Name Formula
Themes names that you specify can be "fuzzy". The text does not have to match exactly what you see printed. For example "Dark Blue 3" and "DarkBlue3" and "dark blue 3" all work.

One way to quickly determine the best setting for your window is to simply display your window using a lot of different themes. Add the line of code to set the theme - theme('Dark Green 1'), run your code, see if you like it, if not, change the theme string to 'Dark Green 2' and try again. Repeat until you find something you like.

The "Formula" for the string is:

Dark Color #

or

Light Color #

Color can be Blue, Green, Black, Gray, Purple, Brown, Teal, Red. The # is optional or can be from 1 to XX. Some colors have a lot of choices. There are 13 "Light Brown" choices for example.

如果您只想更改主题的背景颜色,则可以使用单独的颜色名称或十六进制值。 sg.theme_background_color('#FF0000')sg.theme_background_color('red')会将背景颜色设置为红色。

希望对主题有所帮助。


使用 PSG 编码约定的出色工作。 因此,查看您的代码毫不费力。 对我所看到的进行零猜测。 很高兴看到它在您使用它们时以多种方式提供帮助。

我修改了背景颜色并找到了这个解决方案。

  • 将主题创建为字典
  • 使用 theme_add_new 添加主题function
  • 指定这个主题

编辑的问题代码:

import PySimpleGUI as sg

import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

new_theme = {"BACKGROUND": '#DAE0E6', "TEXT": sg.COLOR_SYSTEM_DEFAULT, "INPUT": sg.COLOR_SYSTEM_DEFAULT,
             "TEXT_INPUT": sg.COLOR_SYSTEM_DEFAULT, "SCROLL": sg.COLOR_SYSTEM_DEFAULT,
             "BUTTON": sg.OFFICIAL_PYSIMPLEGUI_BUTTON_COLOR, "PROGRESS": sg.COLOR_SYSTEM_DEFAULT, "BORDER": 1,
             "SLIDER_DEPTH": 1, "PROGRESS_DEPTH": 0
             }

sg.theme_add_new('MyTheme', new_theme)
sg.theme('MyTheme')


def draw_figure(canvas, fig):
    if canvas.children:
        for child in canvas.winfo_children():
            child.destroy()
    figure_canvas_agg = FigureCanvasTkAgg(fig, master=canvas)
    figure_canvas_agg.draw()
    figure_canvas_agg.get_tk_widget().pack(side='right', fill='both', expand=1)


# ------------------------------- PySimpleGUI CODE

layout = [
    [sg.Text("Population size: "), sg.Input(key="-POPULATIONSIZE-")],
    [sg.Text("Duration: "), sg.Input(key="-DURATION-")],
    [sg.Text("R Number: "), sg.Input(key="-RNUMBER-")],
    [sg.Text("Starting Infections: "), sg.Input(key="-STARTINGINFECTIONS-")],
    [sg.B('OK'), sg.B('Exit')],
    [sg.Canvas(key='controls_cv')],
    [sg.T('Figure:')],
    [sg.Column(
        layout=[
            [sg.Canvas(key='fig_cv',
                       size=(400 * 2, 400)
                       )]
        ],
        # background_color='#DAE0E6',
        pad=(0, 0)
    )],
]

window = sg.Window('Virus Simulation', layout,)

while True:
    event, values = window.read()
    print(event, values)
    if event in (sg.WIN_CLOSED, 'Exit'):
        break
    elif event == 'OK':
        # ------------------------------- PASTE YOUR MATPLOTLIB CODE HERE
        plt.figure(1)
        fig = plt.gcf()
        DPI = fig.get_dpi()
        # ------------------------------- you have to play with this size to reduce the movement error when the mouse hovers over the figure, it's close to canvas size
        fig.set_size_inches(404 * 2 / float(DPI), 404 / float(DPI))
        # -------------------------------
        x = list(range(1, 100))
        y = list(range(1, 100))
        plt.plot(x, y, color="r")
        plt.title('Virus Infections Data')
        plt.xlabel('Time in Days')
        plt.ylabel('Infections')
        plt.grid()

        # ------------------------------- Instead of plt.show()
        draw_figure(window['fig_cv'].TKCanvas, fig,)


window.close()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM