【发布时间】:2021-11-08 01:27:04
【问题描述】:
我正在为我和一个朋友制作的病毒模拟 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()
【问题讨论】:
-
当前的背景颜色是什么?你期望的颜色是什么?
-
您可以使用
sg.theme(theme_name)为您的窗口设置主题,例如sg.theme('LightGreen6'),或者直接在sg.Window中设置选项background_color。您可以通过plt.figure(1, facecolor='green'); ax = plt.axes(); ax.set_facecolor("yellow")为matplotlib设置图形的颜色。 -
由于某种原因
sg.theme(theme_name)不起作用,这很奇怪,因为它通常与 pysimplegui 一起使用。但是,按照您的建议手动为每个元素单独设置颜色似乎工作正常,唯一的问题是它会花费更多时间并且在尝试快速更改配色方案时可能会很乏味。谢谢你帮助我。
标签: python user-interface tkinter pysimplegui