简体   繁体   English

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

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

I'm working on UI for a virus simulation me and a friend are making and I'm really struggling to change the background color of the UI.我正在为我和一个朋友制作的病毒模拟开发 UI,我真的很难改变 UI 的背景颜色。 I took most of the code from the one of the demo projects because i couldn't figure out how to implement matplotlib with pysimplegui so there's some things I don't fully understand but usually with pysimplegui it's as simple as sg.theme="color to change the main background color but it isn't working this time. Any help would be really appreciated, thanks.我从其中一个演示项目中获取了大部分代码,因为我无法弄清楚如何使用 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()

You can change the background color by specifying a Hex Color Code in the following argument under layout :您可以通过在layout下的以下参数中指定十六进制颜色代码来更改背景颜色:

background_color='#DAE0E6'

You can use a Color Picker like this one https://htmlcolorcodes.com/color-picker/ to get your color您可以使用像这样的颜色选择器https://htmlcolorcodes.com/color-picker/来获取您的颜色

You can also use:您还可以使用:

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

To change the color of a window object改变a的颜色 window object

I'm a tad confused in 2 ways.我在两个方面有点困惑。

1 - I don't see a call to sg.theme() in your code, so I don't know where it was in the code. 1 - 我在你的代码中没有看到对sg.theme()的调用,所以我不知道它在代码中的什么位置。 WHERE it is placed matters.它放在哪里很重要。 Always place the theme as early as possible, definitely before making your layout.始终尽早放置主题,绝对是在进行布局之前。 2 - I don't know what "it isn't working this time means". 2 - 我不知道“这次不工作”是什么意思。 Again, it's more of needing to see a complete example to get it.同样,更多的是需要查看完整的示例才能获得它。

The sample code in the question that you said normally works was weirdly formatted so something must have been scrambled.您所说的正常工作的问题中的示例代码格式很奇怪,所以一定是被打乱了。

The question shows: sg.theme="color问题显示: sg.theme="color

But as Jason has pointed out, the value passed to sg.theme() is more than a color.但正如 Jason 指出的那样,传递给sg.theme()的值不仅仅是一种颜色。 The "Theme Name Formula" is described in the main PySimpleGUI documentation here - https://pysimplegui.readthedocs.io/en/latest/#theme-name-formula . “主题名称公式”在此处的主要 PySimpleGUI 文档中进行了描述 - https://pysimplegui.readthedocs.io/en/latest/#theme-name-formula In case there's a problem getting to that section, here's what it says:如果进入该部分时遇到问题,请按以下说明进行操作:

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.

If you want to only change the background color of your theme, then you can use individual color names or hex values.如果您只想更改主题的背景颜色,则可以使用单独的颜色名称或十六进制值。 sg.theme_background_color('#FF0000') or sg.theme_background_color('red') will set the background color to red. sg.theme_background_color('#FF0000')sg.theme_background_color('red')会将背景颜色设置为红色。

Hope that helps with themes.希望对主题有所帮助。


Nice work on using the PSG coding conventions.使用 PSG 编码约定的出色工作。 Looking at your code was effortless as a result.因此,查看您的代码毫不费力。 Zero guesswork as to what I was seeing.对我所看到的进行零猜测。 Great to see and it helps in numerous ways when you use them.很高兴看到它在您使用它们时以多种方式提供帮助。

I tinkered to change the background color and found this solution.我修改了背景颜色并找到了这个解决方案。

  • Create a theme as a dictionary将主题创建为字典
  • Add the theme with theme_add_new function使用 theme_add_new 添加主题function
  • Specify this theme指定这个主题

The question code edited:编辑的问题代码:

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