我正在寻找一些关于在tkinter中创建gui的信息的一些指导,用于我已经在python中编程的图形。我想做的是构建一个可以导入csv数据的gui,然后用户点击一个按钮,显示他们想要的图形类型。现在我有4个图表,我在python中创建,我不知道如何将它们带到tkinter格式。我是python和tkinter的新手。任何指导将不胜感激。 这是我到目前为止为tkinter制作的代码。
import tkinter as tk
from tkinter.filedialog import askopenfilename
from tkinter import *
import pandas as pd
import subprocess
import webbrowser
import sys
def import_csv_data():
global v
csv_file_path = askopenfilename()
print(csv_file_path)
v.set(csv_file_path)
df = pd.read_csv(csv_file_path)
root = tk.Tk()
tk.Label(root, text='File Path').grid(row=0, column=0)
v = tk.StringVar()
entry = tk.Entry(root, textvariable=v).grid(row=0, column=1)
tk.Button(root, text='Browse Data Set',command=import_csv_data).grid(row=1, column=0)
tk.Button(root, text='Close',command=root.destroy).grid(row=1, column=1)
tk.Button(root, text='Graph 1', command=doNothing).grid(row=3, column=0)
tk.Button(root, text='Graph 2', command=doNothing).grid(row=3, column=1)
tk.Button(root, text='Graph 3', command=doNothing).grid(row=3, column=2)
tk.Button(root, text='Graph 4', command=doNothing).grid(row=3, column=3)
def doNothing():
print("nothing")
def create_window():
window = tk.Tk()
menu = Menu(root)
root.config(menu=menu)
subMenu = Menu(menu)
menu.add_cascade(label="File",menu=subMenu)
subMenu.add_command(label="New", command=create_window)
subMenu.add_command(label="Open", command=doNothing)
subMenu.add_command(label="Restart", command=doNothing)
subMenu.add_command(label="Exit", command=doNothing)
editMenu = Menu(menu)
menu.add_cascade(label = "Help", menu=editMenu)
editMenu.add_command(label="Help", command=doNothing)
root.mainloop()
以下是我为其中一张图表编写的代码
import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
df = pd.read_csv('csv.data')
# Indicated your x values and y values.
x = df["X Data"]
y1 = df["Y1 Data"]
y2 = df["Y2 Data"]
z = df["Y3 Data"]
y_pos = np.arange(len(x))
lns1 = plt.bar(y_pos,z)
plt.ylabel('Bar Graph')
plt.xlabel('Date')
plt.twinx()
lns2 = plt.plot(y_pos,y1,'r-',linewidth=2.5)
lns3 = plt.plot(y_pos,y2,color='orange',linewidth=2.5)
plt.ylabel('Line Data')
plt.xticks(y_pos, x)
plt.xlabel('X axis')
plt.title('Graph 1')
plt.legend([lns1, lns2[0], lns3[0]],["Bar", "Line 1", "Line 2"], loc="upper right")
plt.draw()
plt.show()
答案 0 :(得分:1)
import tkinter
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg,NavigationToolbar2Tk)
# Implement the default Matplotlib key bindings.
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
import numpy as np
root = tkinter.Tk()
root.wm_title("Embedding in Tk")
fig = Figure(figsize=(5, 4), dpi=100)
t = np.arange(0, 3, .01)
fig.add_subplot(111).plot(t, 2 * np.sin(2 * np.pi * t))
canvas = FigureCanvasTkAgg(fig, master=root) # A tk.DrawingArea.
canvas.draw()
toolbar = NavigationToolbar2Tk(canvas, root)
toolbar.update()
def on_key_press(event):
print("you pressed {}".format(event.key))
key_press_handler(event, canvas, toolbar)
canvas.mpl_connect("key_press_event", on_key_press)
button = tkinter.Button(master=root, text="Quit", command=root.quit)
# Packing order is important. Widgets are processed sequentially and if there
# is no space left, because the window is too small, they are not displayed.
# The canvas is rather flexible in its size, so we pack it last which makes
# sure the UI controls are displayed as long as possible.
button.pack(side=tkinter.BOTTOM)
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
tkinter.mainloop()
#This is the basic framework type code that helped me. You can use it according to your code.
答案 1 :(得分:0)
这是一种方法(你没有说你想在tkinter窗口中显示图形,所以我假设图形将显示在一个单独的matplotlib窗口中):
display_graph
,它将csv
文件作为参数。然后我
将该模块保存为graph1.py
。以下是graph1.py
代码:
import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Put the code in a function so you cal call it later
def display_graph(data):
df = pd.read_csv(data)
# Indicated your x values and y values.
x = df["X Data"]
y1 = df["Y1 Data"]
y2 = df["Y2 Data"]
z = df["Y3 Data"]
y_pos = np.arange(len(x))
lns1 = plt.bar(y_pos,z)
plt.ylabel('Bar Graph')
plt.xlabel('Date')
plt.twinx()
lns2 = plt.plot(y_pos,y1,'r-',linewidth=2.5)
lns3 = plt.plot(y_pos,y2,color='orange',linewidth=2.5)
plt.ylabel('Line Data')
plt.xticks(y_pos, x)
plt.xlabel('X axis')
plt.title('Graph 1')
plt.legend([lns1, lns2[0], lns3[0]],["Bar", "Line 1", "Line 2"], loc="upper right")
plt.draw()
plt.show()
#display_graph('data.csv')
graph1.py
模块导入到tkinter gui文件中
import graph1
graph_1
,并在display_graph
模块中调用了graph1
。graph_1
。以下是tkinter gui的代码:
注意: 我使用的是python 2.7,因此我更改了一些导入语句,您必须将其更改为python 3等价。
#import Tkinter as tk
#from tkFileDialog import askopenfilename
#from Tkinter import *
import tkinter as tk
from tkinter.filedialog import askopenfilename
from tkinter import *
import pandas as pd
import subprocess
import webbrowser
import sys
import graph1 # import the graph1 module
def import_csv_data():
global v
csv_file_path = askopenfilename()
print(csv_file_path)
v.set(csv_file_path)
df = pd.read_csv(csv_file_path)
# Define the functions before calling them
def doNothing():
print("nothing")
def create_window():
window = tk.Tk()
# Define a function for 'Graph 1' button. This just calls the 'display_graph' function from
# the 'graph1' module.
## You could avoid defining this function and use lambda and graph1.display_graph(v.get())
## in the 'Graph 1' button command but I prefer it this way.
def graph_1():
graph1.display_graph(v.get())
root = tk.Tk()
tk.Label(root, text='File Path').grid(row=0, column=0)
v = tk.StringVar()
entry = tk.Entry(root, textvariable=v).grid(row=0, column=1)
tk.Button(root, text='Browse Data Set',command=import_csv_data).grid(row=1, column=0)
tk.Button(root, text='Close',command=root.destroy).grid(row=1, column=1)
tk.Button(root, text='Graph 1', command=graph_1).grid(row=3, column=0) # Call the graph_1 function
tk.Button(root, text='Graph 2', command=doNothing).grid(row=3, column=1)
tk.Button(root, text='Graph 3', command=doNothing).grid(row=3, column=2)
tk.Button(root, text='Graph 4', command=doNothing).grid(row=3, column=3)
menu = Menu(root)
root.config(menu=menu)
subMenu = Menu(menu)
menu.add_cascade(label="File",menu=subMenu)
subMenu.add_command(label="New", command=create_window)
subMenu.add_command(label="Open", command=doNothing)
subMenu.add_command(label="Restart", command=doNothing)
subMenu.add_command(label="Exit", command=doNothing)
editMenu = Menu(menu)
menu.add_cascade(label = "Help", menu=editMenu)
editMenu.add_command(label="Help", command=doNothing)
root.mainloop()
这是我运行gui脚本,浏览csv文件并点击' Graph 1'按钮:
示例csv文件
X Data,Y1 Data,Y2 Data,Y3 Data
0,5,15,100
2,6,30,125
4,4,20,122
6,10,45,128
8,15,10,79
10,14,10,84
13,20,12,99
14,6,13,56
16,4,18,67
18,8,25,83
20,9,12,91
Tkinter gui
Matplotlib图