Related
am new to Tkinter programming and have written this code.
What i want is, when i click on Start conversation a new page i.e. "Conversation" should be displayed and window should get resized to another geometric coordinates. I have given the geometric coordinates in the topmost class "pythonApp" but am unable to geometric coordinates to resize the windows in other class like "Conversation" page. Can you please tell me how can i resize the "Conversation" page.
Below is my code.
`
import Tkinter as tk
from Tkinter import Label ,BOTH
import time
from PIL import Image
from PIL import ImageTk
import ttk
from wx import Bottom
import datetime as dt
LARGE_FONT = ("Verdana",12)
class pythonApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.geometry("700x500")
tk.Tk.iconbitmap(self, default="accenture.ico") #this is for changing the title bar image
tk.Tk.wm_title(self,"Avatar") #setting up the title
##now creating a container which is going to contain everything
container = tk.Frame(self)
container.pack(side="top",fill="both",expand=True)
container.grid_rowconfigure(0, weight = 1)
container.grid_columnconfigure(0, weight = 1)
#creating a dictionary which willl contain frames so that when we click on Start Conversation a new frame will be loaded
self.frames = {}
#this will loop over every page
for F in (StartPage, PageOne,Conversation):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column = 0 , sticky ="nsew")
self.show_frame(StartPage)
#this function will show the frame that we need
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()# this function brings the page to the front
###################################################section for time elasped module
class ElapsedTimeClock(Label):
def __init__(self, parent, *args, **kwargs):
Label.__init__(self, parent, *args, **kwargs)
self.lastTime = ""
t = time.localtime()
self.zeroTime = dt.timedelta(hours=t[3], minutes=t[4], seconds=t[5])
self.tick()
def tick(self):
# get the current local time from the PC
now = dt.datetime(1, 1, 1).now()
elapsedTime = now - self.zeroTime
time2 = elapsedTime.strftime('%H:%M:%S')
# if time string has changed, update it
if time2 != self.lastTime:
self.lastTime = time2
self.config(text=time2)
# calls itself every 200 milliseconds
# to update the time display as needed
# could use >200 ms, but display gets jerky
self.after(200, self.tick)
####################################end of time elasped module
########This is the 1st page which
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text = "Welcome",font= "LARGE_FONT")
label.pack(pady=10, padx=10)
photo = tk.PhotoImage(file = "howcanihelp.gif")
w = Label(self, image=photo)
w.photo = photo
w.pack()
###########start button$$$$4
conversationbutton = tk.Button(self, text='Start Conversation', height=2, width=40, bg="navy blue", fg="white",
font=("Arial", 10, "bold"),command=lambda:controller.show_frame(Conversation))
conversationbutton.pack(padx=7, pady=7)
chatbutton = tk.Button(self, text='Chat', height=2, width=40, bg="navy blue", fg="white",
font=("Arial", 10, "bold"),command=lambda:controller.show_frame(PageOne))
chatbutton.pack(padx=7, pady=7)
'''stopbutton = tk.Button(self, text='Stop', height=2, width=40, fg="white", bg="navy blue",
font=("Arial", 10, "bold"))
stopbutton.pack(padx=7, pady=7)'''
##################################secound page for chat window
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
#label = tk.Label(self, text = "Chat Page",font= "LARGE_FONT").place()
#label.pack(pady=10, padx=10)
clock = ElapsedTimeClock(self, font=('times', 20, 'bold')).place(x=475,y=350)
#clock.grid(row = 1, column = 1)
#clock.pack(fill=BOTH, expand=1)
photo = tk.PhotoImage(file="agent.gif")
w = Label(self, image=photo)
w.photo = photo
w.place(x=435,y=50)
#w.grid(row = 0, column = 1)
ChatLog = tk.Text(self, bd=0, bg="white", height="8", width="50", font="Arial", )
# ChatLog.insert(END, "Connecting to your partner..\n")
ChatLog.config(state=tk.DISABLED)
# Bind a scrollbar to the Chat window
scrollbar = tk.Scrollbar(self, command=ChatLog.yview, cursor="heart")
ChatLog['yscrollcommand'] = scrollbar.set
# Create the Button to send message
SendButton = tk.Button(self, font=30, text="Send", width="12", height=5, bd=0, bg="#FFBF00",
activebackground="#FACC2E")
# SendButton = Button(base, font=30, text="Send", width="12", height=5,
# bd=0, bg="#FFBF00", activebackground="#FACC2E")
label = tk.Label(self, text="Chat").pack()
def DisableEntry(event):
EntryBox.config(state=tk.DISABLED)
def PressAction(event):
EntryBox.config(state=tk.NORMAL)
# ClickAction()
# Create the box to enter message
EntryBox = tk.Text(self, bd=0, bg="white", width="29", height="5", font="Arial")
EntryBox.bind("<Return>", DisableEntry)
EntryBox.bind("<KeyRelease-Return>", PressAction)
# Place all components on the screen
scrollbar.place(x=376, y=6, height=386)
ChatLog.place(x=6, y=6, height=386, width=370)
EntryBox.place(x=128, y=401, height=90, width=265)
SendButton.place(x=6, y=401, height=90)
stopbutton1 = tk.Button(self, text='Stop', height=2, width=40, fg="white", bg="navy blue",
font=("Arial", 10, "bold"),command=lambda:controller.show_frame(StartPage))
#stopbutton1.pack(padx=7, pady=7)
stopbutton1.place(x=399,y=401)
############################################end of chat page
class Conversation(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text = "Welcome",font= "LARGE_FONT")
label.grid(row=0, column=1 , columnspan=3)
photo = tk.PhotoImage(file = "agent.gif")
w = Label(self, image=photo)
w.photo = photo
#w.pack(side = tk.RIGHT)
w.grid(row=2,column=130 ,rowspan=3,columnspan=3,)
clock = ElapsedTimeClock(self, font=('times', 20, 'bold'))
#clock.pack()
clock.grid(row=3,column=3)
###########start button$$$$4
stopbutton1 = tk.Button(self, text='Stop', height=2, width=40, fg="white", bg="navy blue",
font=("Arial", 10, "bold"), command=lambda: controller.show_frame(StartPage))
#stopbutton1.pack(padx=7, pady=7)
#stopbutton1.grid(row=4,column=3)
app = pythonApp()
app.mainloop()
windowname.geometry("newsizexnewsize")
I have managed to stream a webcam video inside a Wx-Python window using Open-CV but i want to record that video using control buttons. Let me know how to capture a webcam video while a click a button?
import wx
import vlc
import numpy as np
import time
import os
import user
import cv2.cv
class MainWindow(wx.Panel):
def __init__(self, parent,capture):
wx.Panel.__init__(self, parent)
mainSizer = wx.BoxSizer(wx.VERTICAL)
# video
videoWarper = wx.StaticBox(self,size=(640,480))
videoBoxSizer = wx.StaticBoxSizer(videoWarper, wx.VERTICAL)
videoFrame = wx.Panel(self, -1,size=(640,480))
capture = ShowCapture(videoFrame, capture)
videoBoxSizer.Add(videoFrame,0)
mainSizer.Add(videoBoxSizer,0)
parent.Centre()
self.Show()
self.SetSizerAndFit(mainSizer)
# Panels
# The first panel holds the video and it's all black
self.videopanel = wx.Panel(self, -1)
self.videopanel.SetBackgroundColour(wx.BLACK)
# The second panel holds controls
ctrlpanel = wx.Panel(self, -1 )
self.timeslider = wx.Slider(ctrlpanel, -1, 0, 0, 1000)
self.timeslider.SetRange(0, 1000)
pause = wx.Button(ctrlpanel, label="Pause")
play = wx.Button(ctrlpanel, label="Play")
stop = wx.Button(ctrlpanel, label="Stop")
record = wx.Button(ctrlpanel, label="Record")
cancel = wx.Button(ctrlpanel, label="Cancel")
volume = wx.Button(ctrlpanel, label="Vol")
self.volslider = wx.Slider(ctrlpanel, -1, 0, 0, 100, size=(100, -1))
# Bind controls to events
self.Bind(wx.EVT_BUTTON, self.OnPlay, play)
self.Bind(wx.EVT_BUTTON, self.OnPause, pause)
self.Bind(wx.EVT_BUTTON, self.OnStop, stop)
self.Bind(wx.EVT_BUTTON, self.OnRecord, record)
self.Bind(wx.EVT_BUTTON, self.OnCancel, cancel)
self.Bind(wx.EVT_BUTTON, self.OnToggleVolume, volume)
self.Bind(wx.EVT_SLIDER, self.OnSetVolume, self.volslider)
# Give a pretty layout to the controls
ctrlbox = wx.BoxSizer(wx.VERTICAL)
box = wx.BoxSizer(wx.HORIZONTAL)
# box contains some buttons and the volume controls
box.Add(play, flag=wx.RIGHT, border=5)
box.Add(pause)
box.Add(stop)
box.Add(record)
box.Add(cancel)
box.Add((-1, -1), 1)
box.Add(volume)
box.Add(self.volslider, flag=wx.TOP | wx.LEFT, border=5)
# Merge box1 and box2 to the ctrlsizer
ctrlbox.Add(box, flag=wx.EXPAND, border=10)
ctrlpanel.SetSizer(ctrlbox)
# Put everything togheter
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(ctrlpanel, flag=wx.EXPAND | wx.BOTTOM | wx.TOP, border=10)
self.SetSizer(sizer)
self.SetMinSize((350, 300))
# finally create the timer, which updates the timeslider
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)
# VLC player controls
self.Instance = vlc.Instance()
self.player = self.Instance.media_player_new()
def OnClose(self, evt):
"""Closes the window.
"""
self.Close()
def OnOpen(self, evt):
"""Pop up a new dialow window to choose a file, then play the selected file.
"""
# if a file is already running, then stop it.
self.OnStop(None)
# Create a file dialog opened in the current home directory, where
# you can display all kind of files, having as title "Choose a file".
dlg = wx.FileDialog(self, "Choose a file", user.home, "",
"*.*", wx.OPEN)
if dlg.ShowModal() == wx.ID_OK:
dirname = dlg.GetDirectory()
filename = dlg.GetFilename()
# Creation
self.Media = self.Instance.media_new(unicode(os.path.join(dirname, filename)))
self.player.set_media(self.Media)
# Report the title of the file chosen
title = self.player.get_title()
# if an error was encountred while retriving the title, then use
# filename
if title == -1:
title = filename
self.SetTitle("%s - wxVLCplayer" % title)
# set the window id where to render VLC's video output
self.player.set_xwindow(self.videopanel.GetHandle())
# FIXME: this should be made cross-platform
self.OnPlay(None)
# set the volume slider to the current volume
self.volslider.SetValue(self.player.audio_get_volume() / 2)
# finally destroy the dialog
dlg.Destroy()
def OnPlay(self, evt):
"""Toggle the status to Play/Pause.
If no file is loaded, open the dialog window.
"""
# check if there is a file to play, otherwise open a
# wx.FileDialog to select a file
if not self.player.get_media():
self.OnOpen(None)
else:
# Try to launch the media, if this fails display an error message
if self.player.play() == -1:
self.errorDialog("Unable to play.")
else:
self.timer.Start()
def OnPause(self, evt):
"""Pause the player.
"""
self.player.pause()
def OnStop(self, evt):
"""Stop the player.
"""
self.player.stop()
# reset the time slider
self.timeslider.SetValue(0)
self.timer.Stop()
# -------begin capturing and saving video
def OnRecord(self, evt):
capture=cv2.VideoCapture(0)
if (not capture.isOpened()):
print "Error"
# video recorder
# Define the codec and create VideoWriter object
fourcc = cv2.cv.FOURCC('M','P','E','G')
out = cv2.VideoWriter('output.mp4',fourcc, 20.0, (640,480), isColor=True)
while(capture.isOpened()):
ret, frame = capture.read()
if ret==True:
# write the flipped frame
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
def OnCancel(self, evt):
out = cv2.VideoWriter()
capture.release()
out.release()
cv2.destroyAllWindows()
def OnTimer(self, evt):
"""Update the time slider according to the current movie time.
"""
# since the self.player.get_length can change while playing,
# re-set the timeslider to the correct range.
length = self.player.get_length()
self.timeslider.SetRange(-1, length)
# update the time on the slider
time = self.player.get_time()
self.timeslider.SetValue(time)
def OnToggleVolume(self, evt):
"""Mute/Unmute according to the audio button.
"""
is_mute = self.player.audio_get_mute()
self.player.audio_set_mute(not is_mute)
# update the volume slider;
# since vlc volume range is in [0, 200],
# and our volume slider has range [0, 100], just divide by 2.
self.volslider.SetValue(self.player.audio_get_volume() / 2)
def OnSetVolume(self, evt):
"""Set the volume according to the volume sider.
"""
volume = self.volslider.GetValue() * 2
# vlc.MediaPlayer.audio_set_volume returns 0 if success, -1 otherwise
if self.player.audio_set_volume(volume) == -1:
self.errorDialog("Failed to set volume")
class ShowCapture(wx.Panel):
def __init__(self, parent, capture, fps=24):
wx.Panel.__init__(self, parent, wx.ID_ANY, (0,0), (640,480))
self.capture = capture
ret, frame = self.capture.read()
height, width = frame.shape[:2]
parent.SetSize((width, height))
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
self.bmp = wx.BitmapFromBuffer(width, height, frame)
self.timer = wx.Timer(self)
self.timer.Start(1000./fps)
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.Bind(wx.EVT_TIMER, self.NextFrame)
def OnPaint(self, evt):
dc = wx.BufferedPaintDC(self)
dc.DrawBitmap(self.bmp, 0, 0)
def NextFrame(self, event):
ret, frame = self.capture.read()
if ret:
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
self.bmp.CopyFromBuffer(frame)
self.Refresh()
capture = cv2.VideoCapture(0)
app = wx.App(False)
frame = wx.Frame(None, title='CamGUI')
panel = MainWindow(frame,capture)
frame.Show()
app.MainLoop()
I have modified your code so that control buttons come up, are visible and have functions. But you still have to work on the functions. You could also program the slider to jump to the points in the video:
import wx
import vlc
import numpy as np
import sys
import time
import os
import user
import cv2.cv
class MainWindow(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent)
self.size = (640,480)
self.Bind(wx.EVT_CLOSE, self.OnClose)
mainSizer = wx.BoxSizer(wx.VERTICAL)
self.title = title
self.SetTitle(self.title)
self.panel = wx.Panel(self)
# video
self.Playing = False
self.capture = cv2.VideoCapture(0)
self.videoFrame = wx.Panel(self.panel, -1, size=self.size)
image = wx.EmptyImage(self.size[0], self.size[1])
imageBitmap = wx.BitmapFromImage(image)
self.videobmp = wx.StaticBitmap(self.videoFrame, wx.ID_ANY, imageBitmap)
self.ShowCapture()
videoSizer = wx.BoxSizer(wx.HORIZONTAL)
videoSizer.Add(self.videoFrame, 0)
mainSizer.Add(videoSizer, 0)
# The second panel holds controls
ctrlbox = wx.BoxSizer(wx.VERTICAL)
# ctrlpanel = wx.Panel(self, -1 )
self.timeslider = wx.Slider(self.panel, -1, 0, 0, 1000)
self.timeslider.SetRange(0, 1000)
ctrlbox.Add(self.timeslider, flag=wx.EXPAND, border=10)
box = wx.BoxSizer(wx.HORIZONTAL)
pause = wx.Button(self.panel, label="Pause")
play = wx.Button(self.panel, label="Play")
stop = wx.Button(self.panel, label="Stop")
record = wx.Button(self.panel, label="Record")
cancel = wx.Button(self.panel, label="Cancel")
volume = wx.Button(self.panel, label="Vol")
self.volslider = wx.Slider(self.panel, -1, 0, 0, 100, size=(100, -1))
self.volslider.SetValue(50)
# Bind controls to events
self.Bind(wx.EVT_BUTTON, self.OnPlay, play)
self.Bind(wx.EVT_BUTTON, self.OnPause, pause)
self.Bind(wx.EVT_BUTTON, self.OnStop, stop)
self.Bind(wx.EVT_BUTTON, self.OnRecord, record)
self.Bind(wx.EVT_BUTTON, self.OnCancel, cancel)
self.Bind(wx.EVT_BUTTON, self.OnToggleVolume, volume)
self.Bind(wx.EVT_SLIDER, self.OnSetVolume, self.volslider)
# box contains some buttons and the volume controls
box.Add(play, flag=wx.RIGHT, border=5)
box.Add(pause)
box.Add(stop)
box.Add(record)
box.Add(cancel)
box.Add((-1, -1), 1)
box.Add(volume)
box.Add(self.volslider, flag=wx.TOP | wx.LEFT, border=5)
# Merge box1 and box2 to the ctrlsizer
ctrlbox.Add(box, flag=wx.EXPAND, border=10)
# ctrlpanel.SetSizer(ctrlbox)
mainSizer.Add(ctrlbox, 0)
# finally create the timer, which updates the timeslider
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)
# VLC player controls
self.Instance = vlc.Instance()
self.player = self.Instance.media_player_new()
self.panel.SetSizer(mainSizer)
mainSizer.Fit(self)
# self.SetSizerAndFit(mainSizer)
self.Centre()
self.Show()
def OnClose(self, evt):
"""Closes the window.
"""
# self.Close()
self.Destroy()
def OnOpen(self, evt):
"""Pop up a new dialow window to choose a file, then play the selected file.
"""
# if a file is already running, then stop it.
self.OnStop(None)
# Create a file dialog opened in the current home directory, where
# you can display all kind of files, having as title "Choose a file".
dlg = wx.FileDialog(self, "Choose a file", user.home, "",
"*.*", wx.OPEN)
if dlg.ShowModal() == wx.ID_OK:
self.Playing = True
dirname = dlg.GetDirectory()
filename = dlg.GetFilename()
# Creation
self.Media = self.Instance.media_new(unicode(os.path.join(dirname, filename)))
self.player.set_media(self.Media)
# Report the title of the file chosen
title = self.player.get_title()
# if an error was encountred while retriving the title, then use
# filename
if title == -1:
title = filename
self.SetTitle("%s - wxVLCplayer" % title)
# set the window id where to render VLC's video output
# set the window id where to render VLC's video output
# handle = self.videopanel.GetHandle()
handle = self.videoFrame.GetHandle()
if sys.platform.startswith('linux'): # for Linux using the X Server
self.player.set_xwindow(handle)
elif sys.platform == "win32": # for Windows
self.player.set_hwnd(handle)
elif sys.platform == "darwin": # for MacOS
self.player.set_nsobject(handle)
self.OnPlay(None)
# set the volume slider to the current volume
self.volslider.SetValue(self.player.audio_get_volume() / 2)
# finally destroy the dialog
dlg.Destroy()
def OnPlay(self, evt):
"""Toggle the status to Play/Pause.
If no file is loaded, open the dialog window.
"""
# check if there is a file to play, otherwise open a
# wx.FileDialog to select a file
if not self.player.get_media():
self.OnOpen(None)
else:
# Try to launch the media, if this fails display an error message
if self.player.play() == -1:
self.errorDialog("Unable to play.")
else:
self.timer.Start()
self.Playing = True
def OnPause(self, evt):
"""Pause the player.
"""
self.player.pause()
self.Playing = True
def OnStop(self, evt):
"""Stop the player.
"""
self.player.stop()
# reset the time slider
self.timeslider.SetValue(0)
self.timer.Stop()
self.Playing = False
# -------begin capturing and saving video
def OnRecord(self, evt):
# capture=cv2.VideoCapture(0)
if (not self.capture.isOpened()):
print "Error"
# video recorder
# Define the codec and create VideoWriter object
fourcc = cv2.cv.FOURCC('M','P','E','G')
out = cv2.VideoWriter('output.mp4',fourcc, 20.0, (640,480), isColor=True)
while(self.capture.isOpened()):
ret, frame = self.capture.read()
if ret==True:
# write the flipped frame
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
def OnCancel(self, evt):
out = cv2.VideoWriter()
self.capture.release()
out.release()
cv2.destroyAllWindows()
def OnTimer(self, evt):
"""Update the time slider according to the current movie time.
"""
# since the self.player.get_length can change while playing,
# re-set the timeslider to the correct range.
length = self.player.get_length()
self.timeslider.SetRange(-1, length)
# update the time on the slider
time = self.player.get_time()
self.timeslider.SetValue(time)
def OnToggleVolume(self, evt):
"""Mute/Unmute according to the audio button.
"""
is_mute = self.player.audio_get_mute()
self.player.audio_set_mute(not is_mute)
# update the volume slider;
# since vlc volume range is in [0, 200],
# and our volume slider has range [0, 100], just divide by 2.
self.volslider.SetValue(self.player.audio_get_volume() / 2)
def OnSetVolume(self, evt):
"""Set the volume according to the volume sider.
"""
volume = self.volslider.GetValue() * 2
# vlc.MediaPlayer.audio_set_volume returns 0 if success, -1 otherwise
if self.player.audio_set_volume(volume) == -1:
self.errorDialog("Failed to set volume")
def ShowCapture(self, fps=24):
ret, self.frame = self.capture.read()
self.height, self.width = self.frame.shape[:2]
# self.SetSize((self.width, self.height))
self.frame = cv2.cvtColor(self.frame, cv2.COLOR_BGR2RGB)
self.bmp = wx.BitmapFromBuffer(self.width, self.height, self.frame)
self.timer2 = wx.Timer(self)
self.timer2.Start(1000./fps)
# self.Bind(wx.EVT_PAINT, self.OnPaint)
self.Bind(wx.EVT_TIMER, self.NextFrame)
# def OnPaint(self, evt):
# dc = wx.BufferedPaintDC(self)
# dc.DrawBitmap(self.bmp, 0, 0)
def NextFrame(self, event):
if not self.Playing:
ret, self.frame = self.capture.read()
if ret:
self.frame = cv2.cvtColor(self.frame, cv2.COLOR_BGR2RGB)
self.bmp.CopyFromBuffer(self.frame)
self.videobmp.SetBitmap(self.bmp)
self.Refresh()
app = wx.App(False)
frame = MainWindow(None, title='CamGUI')
frame.Show()
app.MainLoop()
I am trying to navigate to the next frame on which new buttons or new labels will be displayed. I mean frame1 should disappear when user clicks any button of the four buttons and frame2 should appear.But the below code does not work.
from Tkinter import *
import tkFileDialog
from PIL import ImageTk, Image
root = Tk()
#my_widget = Widget-name (its container window, ** its configuration options)
def callback():
path = tkFileDialog.askopenfilename()
print path
def create_widgets_in_first_frame():
first_window_label1 = Label(root, text="Analysis of Machine Learning Methods using Titanic Disaster Dataset",justify=CENTER,font=("Helvetica", 20,"bold")).place(x=200,y=20)
first_window_label5 = Label(root, text="Choose your Method:",justify=LEFT,font=("Helvetica", 15,"italic")).place(x=20,y=180)
first_window_label2 = Label(root, text="Upload your Titanic datasets .csv extension here:",justify=LEFT,font=("Helvetica", 15,"italic")).place(x=20,y=60)
first_window_label3 = Label(root, text="Training dataset ->",justify=LEFT,font=("Helvetica", 12)).place(x=50,y=100)
training_data_path = StringVar()
first_window_entry1 = Entry(root, textvariable=training_data_path).place(x=350,y=100)
first_window_button1 = Button(root, text="Browse",command=lambda:training_data_path.set(tkFileDialog.askopenfilename())).place(x=550,y=100)
first_window_label4 = Label(root, text="Testing dataset ->",justify=LEFT,font=("Helvetica", 12)).place(x=50,y=140)
testing_data_path = StringVar()
first_window_entry2 = Entry(root, textvariable=testing_data_path).place(x=350,y=140)
first_window_button2 = Button(root, text="Browse",command=lambda:testing_data_path.set(tkFileDialog.askopenfilename())).place(x=550,y=140)
first_window_button3 = Button(root, text="Decision Tree",font=("Helvetica", 15))
first_window_button3.place(x=50,y=220)
first_window_button3.bind('<Button-1>', call_second_frame_on_top)
first_window_button4 = Button(root, text="Random Forests",font=("Helvetica", 15))
first_window_button4.place(x=350,y=220)
first_window_button4.bind('<Button-1>', call_second_frame_on_top)
first_window_button5 = Button(root, text="Logistic Regression",font=("Helvetica", 15))
first_window_button5.place(x=650,y=220)
first_window_button5.bind('<Button-1>', call_second_frame_on_top)
first_window_button6 = Button(root, text="Analysis",font=("Helvetica", 15))
first_window_button6.place(x=1000,y=220)
first_window_button6.bind('<Button-1>', call_second_frame_on_top)
def create_widgets_in_second_frame():
second_window_label6 = Label(root, text="Decision Trees",justify=CENTER,font=("Helvetica", 20,"bold")).place(x=200,y=20)
print "graph is below"
def call_second_frame_on_top(event):
first_frame.grid_forget()
second_frame.grid(column=0, row=0, padx=20, pady=5)
window_width = 1300
window_heigth = 700
first_frame=Frame(root, width=window_width, height=window_heigth)
first_frame['borderwidth'] = 2
first_frame['relief'] = 'sunken'
first_frame.grid(column=0, row=0, padx=20, pady=5)
second_frame=Frame(root, width=window_width, height=window_heigth)
second_frame['borderwidth'] = 2
second_frame['relief'] = 'sunken'
second_frame.grid(column=0, row=0, padx=20, pady=5)
create_widgets_in_second_frame()
create_widgets_in_first_frame()
second_frame.grid_forget()
#root.minsize(width=1300, height=700)
#root.configure(background='lavender')
root.mainloop()
The problem is that you put all the widgets into root which is the whole window, so when you forget the frame, you forget nothing, as nothing is in the frame.
Just change the root to first_frame
Here is a working code:
from Tkinter import *
import tkFileDialog
from PIL import ImageTk, Image
root = Tk()
#my_widget = Widget-name (its container window, ** its configuration options)
def callback():
path = tkFileDialog.askopenfilename()
print path
def create_widgets_in_first_frame():
first_window_label1 = Label(first_frame, text="Analysis of Machine Learning Methods using Titanic Disaster Dataset",justify=CENTER,font=("Helvetica", 20,"bold")).place(x=200,y=20)
first_window_label5 = Label(first_frame, text="Choose your Method:",justify=LEFT,font=("Helvetica", 15,"italic")).place(x=20,y=180)
first_window_label2 = Label(first_frame, text="Upload your Titanic datasets .csv extension here:",justify=LEFT,font=("Helvetica", 15,"italic")).place(x=20,y=60)
first_window_label3 = Label(first_frame, text="Training dataset ->",justify=LEFT,font=("Helvetica", 12)).place(x=50,y=100)
training_data_path = StringVar()
first_window_entry1 = Entry(first_frame, textvariable=training_data_path).place(x=350,y=100)
first_window_button1 = Button(first_frame, text="Browse",command=lambda:training_data_path.set(tkFileDialog.askopenfilename())).place(x=550,y=100)
first_window_label4 = Label(first_frame, text="Testing dataset ->",justify=LEFT,font=("Helvetica", 12)).place(x=50,y=140)
testing_data_path = StringVar()
first_window_entry2 = Entry(first_frame, textvariable=testing_data_path).place(x=350,y=140)
first_window_button2 = Button(first_frame, text="Browse",command=lambda:testing_data_path.set(tkFileDialog.askopenfilename())).place(x=550,y=140)
first_window_button3 = Button(first_frame, text="Decision Tree",font=("Helvetica", 15))
first_window_button3.place(x=50,y=220)
first_window_button3.bind('<Button-1>', call_second_frame_on_top)
first_window_button4 = Button(first_frame, text="Random Forests",font=("Helvetica", 15))
first_window_button4.place(x=350,y=220)
first_window_button4.bind('<Button-1>', call_second_frame_on_top)
first_window_button5 = Button(first_frame, text="Logistic Regression",font=("Helvetica", 15))
first_window_button5.place(x=650,y=220)
first_window_button5.bind('<Button-1>', call_second_frame_on_top)
first_window_button6 = Button(first_frame, text="Analysis",font=("Helvetica", 15))
first_window_button6.place(x=1000,y=220)
first_window_button6.bind('<Button-1>', call_second_frame_on_top)
def create_widgets_in_second_frame():
second_window_label6 = Label(root, text="Decision Trees",justify=CENTER,font=("Helvetica", 20,"bold")).place(x=200,y=20)
print "graph is below"
def call_second_frame_on_top(event):
first_frame.grid_forget()
second_frame.grid(column=0, row=0, padx=20, pady=5)
window_width = 1300
window_heigth = 700
first_frame=Frame(root, width=window_width, height=window_heigth)
first_frame['borderwidth'] = 2
first_frame['relief'] = 'sunken'
first_frame.grid(column=0, row=0, padx=20, pady=5)
second_frame=Frame(root, width=window_width, height=window_heigth)
second_frame['borderwidth'] = 2
second_frame['relief'] = 'sunken'
second_frame.grid(column=0, row=0, padx=20, pady=5)
create_widgets_in_second_frame()
create_widgets_in_first_frame()
second_frame.grid_forget()
#root.minsize(width=1300, height=700)
#root.configure(background='lavender')
root.mainloop()
Note, that the label you get when you click any buttons is still in the main root so you will have to put that into the second_frame, or wherever you wish.
I am trying to start a graph (which is it's getting data from serial port) on a button's click. I had tried the following code but was not successful. I am new to python. Please help me in guiding were I am wrong.
I am using Python 2.7 with Tkinter
Thanks in advance
import serial
import Tkinter as tk
import ttk
import matplotlib
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import figureCanvasTkAgg
import matplotlib.animation as animation
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
import tkFileDialog
x = []
adc_data = []
f = plt.Figure(figsize = (9,5), dpi = 100)
ax = f.add_subplot(111)
def select(self):
self.BaudRate = self.Baud.get()
self.COMPort = self.COM.get()
self.ser = serial.Serial(port = self.COMPort, baudrate = self.BaudRate,bytesize = serial.EIGHTBITS, stopbits = serial.STOPBITS_ONE, parity = serial.PARITY_NONE)
self.ser.close()
self.ser.open()
self.ser.flushInput();
self.ser.flushOutput();
def quit_(self):
self.ser.close()
def animate_(i):
self.ser.write(str(chr(250)))
data = self.ser.read(1)
data1 = self.ser.read(1)
LSB = ord(data)
MSB = ord(data1)
x.append(LSB)
adc_data.append(MSB) #adding data to list
plt.pause(.00001)
ax.clear()
ax.plot(x,adc_data)
def animate_button(self):
ani = animation.FuncAnimation(f, animate_,interval=1000)
class ADC_Ref_Data(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.wm_geometry(self, '900x600+200+150')
tk.Tk.wm_title(self, "ADC Reference")
container = tk.Frame(self)
container.pack(side="top", fill="both", expand = True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
frame = StartPage(container, self)
self.frames[StartPage] = frame
frame.grid(row=0, column=0, sticky = "nsew")
self.show_frame(StartPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
self.button = ttk.Button(self, text="Stop", state = 'disable',
command=lambda: quit_(self))
self.button.place(relx = 0.97, rely = 0.95, height = 30 , width = 80, anchor = 'se')
button2 = ttk.Button(self, text="Select",
command = lambda:select(self))
button2.place(relx = 0.97, rely = 0.016, height = 30 , width = 80, anchor = 'ne')
button4 = ttk.Button(self, text="Start",
command=lambda: animate_button(self))
button4.place(relx = 0.03, rely = 0.95, height = 30 , width = 80 , anchor = 'sw')
canvas = FigureCanvasTkAgg(f, self)
canvas.show()
canvas.get_tk_widget().place(relx = 0.5, rely = 0.48, relwidth = 1, relheight = 0.8, anchor = 'center' )
app = ADC_Ref_Data()
app.mainloop()
I got success in getting my plot to start on button click.
To get my code working I just need to add a simple line in it which is as follow:
def animate_button(self):
ani = animation.FuncAnimation(f, animate_,frames = 10, interval=1000)
f.canvas.show()
I know this is an old question, but for future travelers: There are a couple functions that are not documented that you can use to control the animation. See this answer for an example of start, stop and pause.
I have the following layout:
btnReset = Button(self.upperButtonFrame, text = "Reset", width = 12, command=self.__parent.reset)
btnReset.grid(row=0, column=0, sticky="W", pady=5)
btnRender = Button(self.upperButtonFrame, text = "Render", width = 9, command = self.render)
btnRender.grid(row=0, column=1, pady=5)
self.bScattered = Radiobutton(self.upperButtonFrame, text="Backscattered", variable=self.plotType, value=1).grid(row=1, column=0, sticky="W")
self.depolarized = Radiobutton(self.upperButtonFrame, text="Depolarized", variable=self.plotType, value=2).grid(row=2, column=0, sticky="W")
self.rng = Label(self.upperButtonFrame, text="Step").grid(row=3, column=0, sticky="W")
self.e = Entry(self.upperButtonFrame).grid(row=3,column=1)
self.to = Label(self.upperButtonFrame, text="to").grid(row=3, column=2)
self.e2 = Entry(self.upperButtonFrame).grid(row=3,column=3)
The problem is my third row looks like:
Instead of evenly spacing the 4 widgets I'm trying to place. How can I fix grid manager cutting off the last two and evenly space them on the screen?
EDIT: Here's a minimal example of my problem, running it should reproduce the results shown above
from Tkinter import Label, Toplevel, Frame, Button, IntVar, \
BOTH, BOTTOM, Radiobutton, Entry, TOP, Tk
CHILDWIDTH = 200
CHILDHEIGHT = 325
class ToolsWindow(Toplevel):
def __init__(self, root):
Toplevel.__init__(self, root)
self.__root = root
self.plotType = IntVar()
self.title("Tools")
self.geometry('%dx%d+%d+%d' % (CHILDWIDTH, CHILDHEIGHT,0, 0))
#self.resizable(width=FALSE, height=FALSE)
self.protocol("WM_DELETE_WINDOW", ToolsWindow.ignore)
self.container = Frame(self, background="red")
self.container.pack(side=TOP, fill=BOTH, expand=True )
self.coordinateFrame = Frame(self.container, background="green", width=50, height=50)
self.coordinateFrame.config(highlightthickness=1) # create a small border around the frame
self.coordinateFrame.config(highlightbackground="grey")
self.coordinateFrame.pack(side=BOTTOM, fill=BOTH, expand=False)
#staticmethod
def ignore():
pass
def setupToolBarButtons(self):
self.upperButtonFrame = Frame(self.container, background="blue") # upper button frame holding text buttons
self.upperButtonFrame.pack(side=TOP)
btnReset = Button(self.upperButtonFrame, text = "Reset", width = 12, command=self.render)
btnReset.grid(row=0, column=0, sticky="w")
btnRender = Button(self.upperButtonFrame, text = "Render", width = 9, command = self.render)
btnRender.grid(row=0, column=1, sticky="w")
self.bScattered = Radiobutton(self.upperButtonFrame, text="Backscattered",
variable=self.plotType, value=1).grid(row=1, column=0, sticky="w")
self.depolarized = Radiobutton(self.upperButtonFrame, text="Depolarized",
variable=self.plotType, value=2).grid(row=2, column=0, sticky="w")
self.rng = Label(self.upperButtonFrame, text="Step")
self.rng.grid(row=3, column=0, sticky="w")
self.e = Entry(self.upperButtonFrame, width=8)
self.e.grid(row=3, column=1, sticky="w")
self.to = Label(self.upperButtonFrame, text="to")
self.to.grid(row=3, column=2, sticky="w")
self.e2 = Entry(self.upperButtonFrame, width=8)
self.e2.grid(row=3, column=3, sticky="w")
def render(self):
pass
root = Tk()
tool = ToolsWindow(root)
tool.setupToolBarButtons()
root.mainloop()
The slightly modified program posted below renders properly, so it must be something in the code you did not post that is causing the problem. Are you limiting the size of the root window's, geometry anywhere? I do not know what you mean by "evenly spaced" but you can use the width parameter on most widgets to increase the size.
from Tkinter import *
class TestIt(object):
def __init__(self, top):
self.upperButtonFrame=top
btnReset = Button(self.upperButtonFrame, text = "Reset", width = 12)
btnReset.grid(row=0, column=0, sticky="W", pady=5)
btnRender = Button(self.upperButtonFrame, text = "Render", width = 9)
btnRender.grid(row=0, column=1, pady=5)
self.bScattered = Radiobutton(self.upperButtonFrame, text="Backscattered").grid(row=1, column=0
self.depolarized = Radiobutton(self.upperButtonFrame, text="Depolarized").grid(row=2, column=0,
self.rng = Label(self.upperButtonFrame, text="Step").grid(row=3, column=0, sticky="e")
self.e = Entry(self.upperButtonFrame).grid(row=3,column=1)
self.to = Label(self.upperButtonFrame, text="to").grid(row=3, column=2, sticky="e")
self.e2 = Entry(self.upperButtonFrame).grid(row=3,column=3)
top = Tk()
TI=TestIt(top)
top.mainloop()